有人可以帮我调整我的SQL以获得所需的结果。我有一个用户表,一个案例表和一个附加到案例的用户的关系表。
用户表 - 用户
+----+-------+--------+
| id | first | last |
+----+-------+--------+
| 1 | Joe | Bloggs |
| 2 | John | Doe |
| 3 | Jane | Doe |
| 4 | Dave | Smith |
+----+-------+--------+
案例表 - 案例
+----+--------+------+
| id | Case | Code |
+----+--------+------+
| 1 | Case 1 | C1 |
| 2 | Case 2 | C2 |
| 3 | Case 3 | C3 |
+----+--------+------+
案例用户表 - case_users
+----+---------+---------+
| id | case_id | user_id |
+----+---------+---------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 4 |
| 4 | 3 | 1 |
| 5 | 1 | 4 |
+----+---------+---------+
我想查询数据库以返回完整的用户列表,如果它们链接到案例1然后案例2案例3等,则返回是或否。
到目前为止我已经获得的SQL(选择案例ID 1)会返回所有用户但是正在分配“不”#39;对每个人:
SELECT
users.first,
users.last,
CASE WHEN case_users.case_id IS NULL THEN 'N' ELSE 'Y' END AS 'yes/no'
FROM
users
LEFT OUTER JOIN case_users ON case_users.case_id = 1
我的实际结果是:
+-------+--------+--------+
| First | Last | Yes/No |
+-------+--------+--------+
| Joe | Bloggs | Y |
| John | Doe | Y |
| Jane | Doe | Y |
| Dave | Smith | Y |
+-------+--------+--------+
我想要的结果应该是:
+-------+--------+--------+
| First | Last | Yes/No |
+-------+--------+--------+
| Joe | Bloggs | Y |
| John | Doe | Y |
| Jane | Doe | N |
| Dave | Smith | Y |
+-------+--------+--------+
有人可以帮助我,因为我无法获得理想的结果吗?
答案 0 :(得分:1)
您错过了从用户到case_users的连接条件:
SELECT
users.first,
users.last,
CASE WHEN case_users.case_id IS NULL THEN 'N' ELSE 'Y' END AS 'yes/no'
FROM
users
LEFT OUTER JOIN case_users ON users.id = case_users.user_id AND case_users.case_id = 1
答案 1 :(得分:1)
你可以试试这个。
SELECT u.first, u.last, IF(cu.case_id,'Y','N') AS CASE_1 FROM users u
LEFT JOIN case_users cu ON u.id = cu.user_id AND cu.case_id = 1
也可以使用IF(cu.case_id,'Y','N')
条件代替CASE
答案 2 :(得分:0)
SELECT u.*
, CASE WHEN cu.case_id IS NULL THEN 'N' ELSE 'Y' END linked
FROM users u
JOIN cases c
LEFT
JOIN case_users cu
ON cu.user_id = u.id
AND cu.case_id = c.id
WHERE c.id = 1;