LEFT JOIN返回空结果集

时间:2012-04-13 11:48:45

标签: sql postgresql left-join

我对连接有一个小的逻辑问题。我有一个回答答案的数据库。架构是:

Question
question_id
question_text

Answers
answer_id
question_id
answer_text

User Responses
user_id
answer_id
question_id

我正在尝试查找用户尚未回答的问题但我一直收到空回复。查询如下:

SELECT * FROM questions 
    LEFT JOIN responses ON questions.question_id = responses.question_id 
WHERE user_id != '1'

我的逻辑在哪里出错?

6 个答案:

答案 0 :(得分:2)

尝试使用IS NULL进行LEFT JOIN

SELECT q.question_id FROM questions q
    LEFT JOIN responses r ON q.question_id = r.question_id AND r.user_id = 1
WHERE r.question_id IS NULL

答案 1 :(得分:2)

使用用户ID 1

获取用户未回答的问题
SELECT * FROM questions 
    LEFT JOIN responses ON questions.question_id = responses.question_id 
WHERE responses.question_id IS NULL AND user_id = 1

答案 2 :(得分:1)

而不是使用左连接,而是使用子查询。这就是你在MS SQL中的表现 - 你可能需要调整MySQL。

SELECT * FROM questions WHERE question_id NOT IN (
    SELECT question_id FROM responses WHERE user_id = 1
)

左边连接,你需要检查右表中的值可能会让你头疼。对于这种特定类型的查询,我发现以这种方式查询更容易,更可靠。

答案 3 :(得分:1)

另一种可能性是EXISTS半连接。

SELECT *
FROM   questions q
WHERE  NOT EXISTS (
   SELECT * 
   FROM   responses r
   WHERE  r.question_id = q.question_id
   AND    r.user_id = 1
   );

答案 4 :(得分:0)

试试这个:

Select * 
from Question
where question_id not in (select question_id from Responses where user_id=1)

答案 5 :(得分:0)

试试这个

SELECT * FROM questions 
LEFT JOIN responses ON questions.question_id = responses.question_id AND 
user_id != '1'

使用where at end将导致过滤两个表,结果为null。