我有两个表:users
和tasks
表users
:
+----------+---------------------+
| id | usrname |
+----------+---------------------+
| 1 | user1 |
+----------+---------------------+
| 2 | user2 |
+----------+---------------------+
| 3 | user3 |
+----------+---------------------+
| 4 | user4 |
+----------+---------------------+
表tasks
+----------+-------------------+-------------------+-------------------+
| id | users | task | calenderweek |
+----------+-------------------+-------------------+-------------------+
| 1 | user1 | task1 | 48 |
+----------+-------------------+-------------------+-------------------+
| 2 | user1 | task2 | 49 |
+----------+-------------------+-------------------+-------------------+
| 3 | user2 | task1 | 50 |
+----------+-------------------+-------------------+-------------------+
| 4 | user1 | task3 | 50 |
+----------+-------------------+-------------------+-------------------+
现在,即使没有给定日历周的条目,我现在也要显示所有用户及其任务。
outout应该看起来像这样:
日历周(50)的输出:
+----------+-------------------+-------------------+
| id | users | task |
+----------+-------------------+-------------------+
| 1 | user1 | task3 |
+----------+-------------------+-------------------+
| 2 | user2 | task1 |
+----------+-------------------+-------------------+
| 3 | user3 | no task |
+----------+-------------------+-------------------+
| 4 | user4 | no task |
+----------+-------------------+-------------------+
我想我需要Left join和COALESCE的组合,但是我从未使用过它们,并且结果为空或语法错误。
我尝试了很多事情,以至于我想不清了哈哈 目前我的查询如下:
SELECT *, COALESCE(tasks.task, 'no tasks') FROM users LEFT JOIN tasks ON users.usrname = tasks.users WHERE tasks.calenderweek = '50'
那么最好的方法是什么?
答案 0 :(得分:-1)
您快到了。 This应该可以解决问题:
SELECT *, COALESCE(tasks.task, 'no tasks') FROM users LEFT JOIN tasks ON users.usrname = tasks.users AND tasks.calenderweek = '50'
问题是您在calenderweek
子句中对WHERE
进行了过滤。因此,任何没有任务的用户都将被排除在结果之外。如果将条件放在JOIN
中,则会选择所有用户,并且所有没有任务的用户都将获得no tasks
。