基本上,有以下结构的三个表
第一个表:tournament_questions,包含所有问题
id tournament_id question active created_at updated_at
1 5 Text question 1 2018-12-08 20:28:49 NULL
第二个表:tournament_options,具有所有选项
id question_id option correct active created_at updated_at
1 1 1 1 1 2018-12-08 20:29:02 NULL
2 1 26 0 1 2018-12-08 20:29:02 NULL
第三个表:tournament_user_answers,包含所有用户答案。
id option_id user_id score active created_at updated_at
该表目前没有数据。
我想实现用户未回答的所有问题,因此查询应返回第一个问题。这是我尝试过的查询,但它总是返回 null
SELECT * FROM tournament_user_answers
INNER JOIN tournament_options ON tournament_user_answers.option_id =
tournament_options.id AND tournament_options.active = 1
LEFT JOIN tournament_questions ON tournament_questions.id =
tournament_options.question_id AND tournament_questions.active = 1
WHERE tournament_questions.tournament_id = 5 AND
tournament_questions.active = 1
AND tournament_questions.id IS NULL AND tournament_user_answers.user_id = 1
LIMIT 1
最佳答案
您从 FROMtournament_user_answers
(空)开始,然后执行 LEFT JOIN
,其中包含左侧的所有行(空)并附加到这些行右侧的数据(如果有)。 空的 LEFT JOIN 数据
将为空。
SELECT
tournament_questions.*
FROM tournament_questions
JOIN tournament_options
ON tournament_options.question_id = tournament_questions.id
AND tournament_options.active = 1
LEFT JOIN tournament_user_answers
ON tournament_user_answers.option_id = tournament_options.id
AND tournament_user_answers.user_id = 1
WHERE
tournament_questions.tournament_id = 5
AND tournament_questions.active = 1
GROUP BY tournament_questions.id
HAVING MAX(tournament_user_answers.id) IS NULL
ORDER BY tournament_questions.id ASC
在这种情况下,左侧部分(问题+选项)包含数据,并且如果有答案,则会附加答案。通过在您的 HAVING
中包含 MAX(tournament_user_answers.id) IS NULL
,您会得到所有没有答案的问题。
关于mysql - 如果没有得到解答就提出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53683939/