基本上,有三个具有以下结构的表
第一张表:Tournament_questions,所有问题
id tournament_id question active created_at updated_at
1 5 Text question 1 2018-12-08 20:28:49 NULL
第二张表:具有所有选项的比赛选项
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
任何人,谢谢您的帮助。
答案 0 :(得分:1)
以FROM tournament_user_answers
(空)开始,然后执行LEFT JOIN
,其中包括左手所有行(空),并在这些行的后面附加数据(如果有) 。 empty LEFT JOIN data
将为空。
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
在这种情况下,左侧部分(问题+选项)具有数据,如果有答案,则会附加答案。通过在您的MAX(tournament_user_answers.id) IS NULL
中加入HAVING
,您将得到所有没有答案的问题。
答案 1 :(得分:0)
也许这对您的情况适用(简化版):
SELECT q.id, q.question, ua.id ua_id FROM tournament_questions q
INNER JOIN tournament_options o ON q.id = o.question_id
LEFT JOIN tournament_user_answers ua ON o.id = ua.option_id
GROUP BY q.id
HAVING ua_id IS NULL