2

我有两张桌子:

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

显然这会返回所有记录。我卡在这里如何进行此查询。

4

4 回答 4

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
于 2012-11-15T14:05:39.393 回答
2

如果您不必使用JOIN操作,那么您可以尝试一下

想要获取特定用户尚未回答的所有问题:

select * from question
where
    question_id not in (select distinct question_id from question_answer where user_id=$userId);

请参阅 Sqlfiddle 上的演示

不知道not in是比JOIN操作慢还是快。

于 2012-11-15T14:36:57.370 回答
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;
于 2012-11-15T14:26:03.150 回答
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;

SQL 小提琴演示

这会给你一些还没有答案的问题

但是,如果您想获得尚未回答问题的用户,您应该JOIN在 users 表中添加一个额外的内容。就像是:

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;

更新的 SQL Fiddle 演示

于 2012-11-15T14:03:54.730 回答