我有一個USERS(醫生和護士),患者和任務表的數據庫:MySQL的選擇子查詢或加入
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是返回全體護士的每一行:
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
此問題未顯示任何研究工作。 **做你的作業很重要**。告訴我們你發現了什麼,***爲什麼它不符合你的需求。這表明你已經花時間去嘗試幫助你自己了,它使我們避免重申明顯的答案,最重要的是它可以幫助你得到更具體和相關的答案。 [FAQ](http://stackoverflow.com/questions/how-to-ask)。 –
您的查詢包括一個叫做'dependents'表 - 是一樣的'patients'? –