MySQL选择子查询或联接

时间:2013-05-20 13:12:59

标签: mysql sql

我有一个包含USERS(医生和护士),PATIENTS和ASSIGNMENTS表的数据库:

USERS (id, etc.)
PATIENTS (id, doctorid, etc.)
ASSIGNMENTS (id, patientid, doctorid, nurseid, etc.)

当医生登录时,他需要查看他的患者名单以及分配给该患者的NURSE或NURSES。结果应如下所示:

+--------------------+--------------------+-------------------+
| 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

1 个答案:

答案 0 :(得分:0)

assignments的加入条件不包含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