我有一个包含用户(医生和护士)、患者和分配表的数据库:
USERS (id, etc.)
PATIENTS (id, doctorid, etc.)
ASSIGNMENTS (id, patientid, doctorid, nurseid, etc.)
当医生登录时,他需要查看他的患者列表以及分配给该患者的护士。结果应如下所示:
+--------------------+--------------------+-------------------+
| patient first name | patient last name | assigned nurses |
+--------------------+--------------------+-------------------+
| john | doe | nurse 1, nurse 2 |
| jim | jones | nurse 7 |
| john | doe | nurse 4, nurse 5 |
| jim | jones | nurse 3 |
| jim | jones | nurse 6 |
+--------------------+--------------------+-------------------+
我将如何编写 sql 来返回这些数据?
我的 sql 正在返回每一行的所有 NURSES:
SELECT a.id, a.doctorid, a.firstname, a.lastname, GROUP_CONCAT(distinct c.firstname, ' ', c.lastname) as assignednurse
FROM dependents a
JOIN (
SELECT ass.id, ass.dependentid, ass.nurseid
FROM assignments ass
) b ON (a.doctorid = 22)
JOIN (
u.id, u.doctorid, u.firstname, u.lastname
FROM users u
GROUP BY u.id
) c ON (c.id = b.nurseid)
GROUP BY a.id