这些是我的表格:
表任务
id label
----------
1 Task 1
2 Task 2
3 Task 3
4 Task 4
5 Task 5
6 Task 6
7 Task 7
7 Task 8
表user_tasks
id id_user id_task
------------------
1 1 1
2 1 2
3 1 4
4 2 1
5 3 1
我有这个我认为有效的查询:
SELECT t.id, t.label as text, IF(u.id_user IS NULL, 0, 1) as done
FROM tasks AS t
LEFT JOIN user_tasks AS u ON t.id = u.id_task
WHERE u.id_user = 1
OR u.id_user IS NULL
ORDER BY id DESC
因此,如果我运行该查询,我会得到这个成功的回复:
id text done
----------------
8 Task 8 0
7 Task 7 0
6 Task 6 0
5 Task 5 0
4 Task 4 1
3 Task 3 0
2 Task 2 1
1 Task 1 1
但是如果我把另一个没有完成任务的用户ID,例如5,我得到这个结果:
id text done
----------------
8 Task 8 0
7 Task 7 0
6 Task 6 0
5 Task 5 0
3 Task 3 0
所有任务,减去已在user_tasks表上为不同用户设置的任务。
我做错了什么? 谢谢!
答案 0 :(得分:1)
将u.id_user = 1
移至ON
子句,然后移除WHERE
子句(包括u.id_user IS NULL
。)
SELECT t.id, t.label as text, IF(u.id_user IS NULL, 0, 1) as done
FROM tasks AS t
LEFT JOIN user_tasks AS u ON t.id = u.id_task AND u.id_user = 1
ORDER BY id DESC