-3

我有一个包含用户(医生和护士)、患者和分配表的数据库:

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
4

1 回答 1

0

您的连接条件 toassignments不包括来自 的字段assignments,因此它本质上是交叉/笛卡尔连接。此外,您正在执行似乎不需要的子查询 - 这不应该影响返回的值,但可能会降低性能,并使维护更加困难。相反,请尝试:

SELECT a.id, 
       a.doctorid, 
       a.firstname, 
       a.lastname, 
       GROUP_CONCAT(distinct c.firstname, ' ', c.lastname) as assignednurse
FROM patients a
LEFT JOIN assignments b ON a.id = b.patientid
LEFT JOIN users c ON c.id = b.nurseid
WHERE a.doctorid = 22
GROUP BY a.id
于 2013-05-20T13:30:51.097 回答