我试过这个问题:在不到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
;
感谢。
答案 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