我有两张桌子:
question
question_id | question
question_answer
answer_id | question_id | choice_id | user_id | explain
我想获得特定用户尚未回答的所有问题。
SELECT question, question_id as questionId
FROM question q
LEFT JOIN question_answer qa USING(question_id)
WHERE qa.user_id!=$userId
我在这种情况下得到零行。我也试过了
SELECT question, q.question_id as questionId
FROM question q
LEFT JOIN question_answer qa ON q.question_id=qa.question_id AND qa.user_id!=$userId
显然这会返回所有记录。我坚持在这里如何进行此查询。
答案 0 :(得分:2)
您检查特定用户的LEFT JOIN
部分应该是相反的,即user_id = $userId
而不是user_id <> $userId
。
在结果行中,您可以选择user_id IS NULL
来查找$userId
尚未回答的问题。
SELECT question, q.question_id as questionId
FROM question q
LEFT JOIN question_answer qa ON q.question_id=qa.question_id AND qa.user_id=$userId
WHERE qa.user_id IS NULL
答案 1 :(得分:2)
如果您不一定要使用JOIN
操作,那么您可以在
想要获得特定用户未回答的所有问题 又:
select * from question
where
question_id not in (select distinct question_id from question_answer where user_id=$userId);
不知道not in
是否比JOIN
操作更慢或更快。
答案 2 :(得分:1)
请改为尝试:
SELECT question, q.question_id as questionId
FROM question q
LEFT JOIN question_answer qa ON q.question_id = qa.question_id
WHERE qa.user_id IS NULL;
这将为您提供 问题但没有答案 。
但是,如果您希望获得尚未回答问题的用户,则应该向users表额外添加JOIN
。类似的东西:
SELECT u.id, u.name
FROM users u
LEFT JOIN question_answer qa ON qa.user_id = u.id
WHERE qa.question_id IS NULL;
答案 3 :(得分:1)
我会将上述MG的答案修改为
SELECT question, q.question_id as questionId
FROM question q
LEFT JOIN question_answer qa ON q.question_id = qa.question_id
and qa.user_id=2
WHERE qa.user_id IS NULL;