1

假设我有 2 个用于用户和任务的表。任务中有 user_id 和状态,状态可能值为“完成”和“未完成”。现在我想检索甚至没有完成一项任务的用户。最粗略的方法是首先找到至少完成 1 个任务的用户并运行“不在”查询。

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

4

3 回答 3

1
SELECT *
FROM users u
WHERE NOT EXISTS (
    SELECT * FROM tasks t
    WHERE t.user_id = u.user_id
    AND t.status = 'complete'
    );
于 2013-09-14T15:05:33.063 回答
1

task.user_id不能包含 NULL(即有NOT NULL约束)时,LEFT JOINwithIS NULL是您的最佳选择

SELECT user.* FROM user
LEFT JOIN task ON (task.user_id = user.id AND task.status = 'complete')
WHERE task.user_id IS NULL
于 2013-09-15T06:03:38.003 回答
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

查看任务完成用户的小提琴

未完成任务的用户见 fiddle

于 2013-09-14T14:20:51.930 回答