需要返回负集的mysql join查询

时间:2013-09-14 14:02:51

标签: mysql sql join

假设我有2个表供用户使用任务。有user_id&具有可能值“完成”的状态的任务状态& “不完整”。 现在我想检索甚至没有完成任务的用户。 最粗略的方法是首先找到至少有一个完整任务并运行“不在”查询的用户。

没有“in”子查询的任何更好的方法来实现这一点。请注意,数据集很大,我无法长时间锁定任务表!

3 个答案:

答案 0 :(得分:1)

SELECT *
FROM users u
WHERE NOT EXISTS (
    SELECT * FROM tasks t
    WHERE t.user_id = u.user_id
    AND t.status = 'complete'
    );

答案 1 :(得分:1)

如果task.user_id不能包含NULL(即NOT NULL约束),LEFT JOIN IS NULL就是best choice

SELECT user.* FROM user
LEFT JOIN task ON (task.user_id = user.id AND task.status = 'complete')
WHERE task.user_id IS NULL

答案 2 :(得分:0)

尝试以下查询将列出已完成1个任务或超过1个

的用户
SELECT u.*,
COUNT(  CASE WHEN  t.`status`= 'Completed' THEN t.`status` END  ) AS completed ,

COUNT(  CASE WHEN  t.`status`= 'Not completed' THEN t.`status` END  ) AS Not_completed

FROM `user`  u

LEFT JOIN `task` t  ON (u.id =t.user_id)

GROUP BY t.user_id HAVING completed >0

这将列出那些尚未完成任务的用户

SELECT u.*,
COUNT(  CASE WHEN  t.`status`= 'Completed' THEN t.`status` END  ) AS completed ,

COUNT(  CASE WHEN  t.`status`= 'Not completed' THEN t.`status` END  ) AS Not_completed

FROM `user`  u

LEFT JOIN `task` t  ON (u.id =t.user_id)

GROUP BY t.user_id HAVING completed = 0

See fiddle for task completed users

See fiddle for users that have not completed task