我需要将LEFT JOIN
查询与NOT IN
查询结合起来,并且必须从这些查询中获取结果值。我在单独使用这两个查询时得到了正确的结果。
我有两张表user
和answer
user
表
user_id
1
2
3
4
5
answer
表
user_id date
1 2015-10-15 21:23:14
2 2015-10-15 20:23:14
3 2015-11-11 16:23:14
LEFT JOIN
查询:
SELECT user.user_id
FROM user
LEFT JOIN answer
ON user.user_id = answer.user_id
WHERE DATEDIFF(NOW(),answer.date) > 5
此查询返回结果user_id
1,2。
NOT IN
查询:
SELECT user.user_id
FROM user
WHERE user.user_id NOT IN (SELECT answer.user_id FROM answer)
此查询返回结果user_ids
4,5。
我需要将这两个查询合并为单个查询,因此我尝试了以下两个查询:
SELECT user.user_id
FROM user
LEFT JOIN answer
ON user.user_id = answer.user_id
WHERE (DATEDIFF(NOW(),answer.date) > 5
AND user.user_id NOT IN (SELECT answer.user_id FROM answer))
和
SELECT user.user_id
FROM user
LEFT JOIN answer
ON user.user_id = answer.user_id
WHERE user.user_id NOT IN (SELECT answer.user_id FROM answer)
AND DATEDIFF(NOW(),answer.date) > 5
但这些返回空user_id
。
修改
预期结果应包含1,2,4,5
答案 0 :(得分:2)
如果您的意思是要将2个选项组合在一起,请尝试全部联盟 / 联盟:
SELECT * FROM
(
SELECT [WITH YOUR LEFT JOIN STATEMENT]
UNION
SELECT [WITH YOUR NOT IN STATEMENT]
) ResultTABLE
答案 1 :(得分:1)
如果您参考WHERE
子句中的答案表,answer.date
将被限制为非NULL值,使LEFT JOIN
的行为类似于常规连接。将条件移至ON
条件以检索所有用户,以及可能 answers
中的匹配行:
SELECT user.user_id
FROM user u
LEFT JOIN answer a ON u.user_id = a.user_id
AND DATEDIFF(NOW(),a.date) < 5
;
编辑:在编辑问题之后,OP似乎希望连接记录与不存在的答案或answer.date太旧/年轻:
SELECT user.user_id
FROM user u
LEFT JOIN answer a ON u.user_id = a.user_id
WHERE a.date IS NULL -- no answer record
OR DATEDIFF(NOW(),a.date) > 5 -- too old answer record
;
最终版本:由于OP希望找到没有(最近)答案的用户,因此查询可以简化为:
SELECT user.user_id
FROM user u
WHERE NOT EXISTS (
SELECT * FROM answer a
WHERE a.user_id = u.user_id
AND DATEDIFF(NOW(), a.date) <= 5
);
答案 2 :(得分:1)
您的查询是正确的方法,但您只需将AND
替换为OR
:
SELECT user.user_id
FROM user
LEFT JOIN answer
ON user.user_id = answer.user_id
WHERE user.user_id NOT IN (SELECT answer.user_id FROM answer)
OR DATEDIFF(NOW(),answer.date) > 5
在这里,您可以找到一个有效的解决方案:http://sqlfiddle.com/#!9/2519b/5/0