2

我试过这个查询:在少于 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
;    

谢谢。

4

1 回答 1

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
于 2012-11-24T11:08:21.857 回答