SQL有COUNT和JOIN

时间:2012-11-24 11:01:43

标签: sql dml

我试过这个问题:在不到2家医院工作的医生是什么?但结果并不是我的预期。

我有这些表格:

CREATE TABLE Hospital (
    hid INT PRIMARY KEY,
    name VARCHAR(127) UNIQUE,
    country VARCHAR(127),
    area INT
);
CREATE TABLE Doctor (
    ic INT PRIMARY KEY,
    name VARCHAR(127),
    date_of_birth INT,
);
CREATE TABLE Work (
    hid INT,
    ic INT,
    since INT,
    FOREIGN KEY (hid) REFERENCES Hospital (hid),
    FOREIGN KEY (ic) REFERENCES Doctor (ic),
    PRIMARY KEY (hid,ic)
);

我试过这个:

SELECT DISTINCT D.ic 
    FROM Doctor D, Work W 
    JOIN Hospital H ON (H.hid = W.hid)
    WHERE D.bi = W.bi
    GROUP BY (D.ic)
    HAVING COUNT(H.hid) < 2
;    

感谢。

1 个答案:

答案 0 :(得分:6)

您需要使用LEFT JOIN并且加入表格Hospital并非必要

SELECT  a.name
FROM    Doctor a
        LEFT JOIN `Work` b
            ON a.ic = b.ic
GROUP BY a.name
HAVING COUNT(b.ic) < 2