mysql - 如果没有得到解答就提出问题

标签 mysql

基本上,有以下结构的三个表

第一个表: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/

相关文章:

mysql - 如何将所有 50 个州设置为国家代码为 'US'

MYSQL,如何获取ID大于4的数据

java - 在处理遗留数据库时,Hibernate 会因丢失的行而窒息

mysql - 在 MySQL 中使用非标准日期时间格式

mysql - SQL Server 2008 排序规则

c# - 如何用C#命令控制服务中存在Mysql Server?

Mysql最近一小时数据

php - 如何在 PHP 中显示 MySQL Select 语句结果

php - 文件上传返回值

java - android editText文本在mysql数据库中显示为0?