两个表,一个包含问题,另一个包含每个用户的答案,如果他们已经回答了它。我正在尝试按下权重(最重要的)排序下一个问题,其中用户a在答案表中没有答案。
我的表格如下:
table: app_questions
| id | int(11) | NO | PRI | NULL | auto_increment |
| owneruid | int(11) | YES | | NULL | |
| question | varchar(350) | YES | | NULL | |
| answer_1 | varchar(350) | YES | | NULL | |
| answer_2 | varchar(350) | YES | | NULL | |
| answer_3 | varchar(350) | YES | | NULL | |
| answer_4 | varchar(350) | YES | | NULL | |
| weight | decimal(5,2) | YES | | NULL | |
| datetime | datetime | YES | | NULL | |
table: app_answers
| id | int(11) | NO | PRI | NULL | auto_increment |
| uid | int(11) | YES | | NULL | |
| quid | int(11) | YES | | NULL | |
| answer | int(11) | YES | | NULL | |
| importance | int(11) | YES | | NULL | |
| answer_status | varchar(20) | YES | | NULL | |
| answer_explanation | varchar(200) | YES | | NULL | |
| datetime | datetime | YES | | NULL | |
我尝试了一些变化,但还没有得到我需要的东西:
SELECT uid ,
question ,
answer_1 ,
answer_2 ,
answer_3 ,
answer_4 ,
weight ,
answer_status
FROM match_questions
LEFT JOIN match_answers ON match_questions.id = match_answers.quid
WHERE answer_status IS NULL
AND EXISTS ( SELECT *
FROM match_answers
WHERE uid = 1 )
ORDER BY weight DESC LIMIT 1;
SELECT uid ,
question ,
answer_1 ,
answer_2 ,
answer_3 ,
answer_4 ,
weight ,
answer_status
FROM match_questions
LEFT JOIN match_answers ON match_questions.id = match_answers.quid
WHERE uid IS NULL
AND answer_status IS NULL
ORDER BY weight DESC LIMIT 1;
SELECT uid ,
question ,
answer_1 ,
answer_2 ,
answer_3 ,
answer_4 ,
weight ,
answer_status
FROM match_questions
LEFT JOIN match_answers ON match_questions.id = match_answers.quid
WHERE answer_status IS NULL
AND uid IS NULL
ORDER BY weight DESC LIMIT 1;
任何指导意见。
答案 0 :(得分:1)
在没有看到样本数据和所需输出的情况下很难分辨,但恕我直言,您的查询可能看起来像这样
SELECT q.id,
q.question,
q.answer_1,
q.answer_2,
q.answer_3,
q.answer_4,
q.weight
FROM match_questions q LEFT JOIN match_answers a
ON q.id = a.quid
AND a.uid = 1
WHERE a.quid IS NULL
ORDER BY q.weight, q.id
LIMIT 1
这是 SQLFiddle 演示