我有一个表“人”,一个关联表“person_vaccination”和一个表“疫苗接种”。
我想找到那些缺少疫苗接种的人,但到目前为止我只有在我有身份证时才能上班。
SELECT vac.VACCINATION_Name
FROM VACCINATION vac
WHERE vac.VACCINATION_NUMBER NOT IN
(SELECT v.VACCINATION_NUMBER
FROM PERSON per
Join PERSON_VACCINATION pv ON per.PERSON_NUMBER = pv.PERSON_NUMBER
JOIN VACCINATION v ON pv.VACCINATION_NUMBER = v.VACCINATION_NUMBER
WHERE per.PERSON_NUMBER = 6)
它工作正常,但我如何让所有人错过接种疫苗? (例如: 555,疫苗接种1 555,疫苗接种2 666,疫苗接种1)
答案 0 :(得分:2)
Oracle 11g R2架构设置:
CREATE TABLE VACCINATION ( VACCINATION_NUMBER, VACCINATION_NAME ) AS
SELECT 1, 'Vac 1' FROM DUAL
UNION ALL SELECT 2, 'Vac 2' FROM DUAL
UNION ALL SELECT 3, 'Vac 3' FROM DUAL
UNION ALL SELECT 4, 'Vac 4' FROM DUAL;
CREATE TABLE PERSON_VACCINATION ( VACCINATION_NUMBER, PERSON_NUMBER ) AS
SELECT 1, 1 FROM DUAL
UNION ALL SELECT 2, 1 FROM DUAL
UNION ALL SELECT 3, 1 FROM DUAL
UNION ALL SELECT 4, 1 FROM DUAL
UNION ALL SELECT 1, 2 FROM DUAL
UNION ALL SELECT 2, 2 FROM DUAL
UNION ALL SELECT 3, 2 FROM DUAL;
CREATE TABLE PERSON ( PERSON_NUMBER, PERSON_NAME ) AS
SELECT 1, 'P1' FROM DUAL
UNION ALL SELECT 2, 'P2' FROM DUAL
UNION ALL SELECT 3, 'P3' FROM DUAL;
查询1 :
SELECT p.PERSON_NAME,
v.VACCINATION_NAME
FROM VACCINATION v
CROSS JOIN
PERSON p
WHERE NOT EXISTS ( SELECT 1
FROM PERSON_VACCINATION pv
WHERE pv.VACCINATION_NUMBER = v.VACCINATION_NUMBER
AND pv.PERSON_NUMBER = p.PERSON_NUMBER )
ORDER BY p.PERSON_NAME,
p.PERSON_NUMBER,
v.VACCINATION_NAME,
v.VACCINATION_NUMBER
<强> Results 强>:
| PERSON_NAME | VACCINATION_NAME |
|-------------|------------------|
| P2 | Vac 4 |
| P3 | Vac 1 |
| P3 | Vac 2 |
| P3 | Vac 3 |
| P3 | Vac 4 |
答案 1 :(得分:0)
不应使用INNER JOIN,而应使用LEFT JOIN。
答案 2 :(得分:0)
如果您完全没有接种疫苗的人,那么您可以在PERSON和PERSON_VACCINATION之间使用LEFT OUTER JOIN,然后找到PERSON_VACCINATION列为NULL的所有条目。
SELECT PERSON_NUMBER
FROM PERSON P
LEFT OUTER JOIN
PERSON_VACCINATION PV
ON P.PERSON_NUMBER = PV.PERSON_NUMBER
WHERE PV.PERSON_NUMBER IS NULL
如果您不熟悉LEFT OUTER JOIN,它会尝试在PERSON_VACCINATION中为PERSON中的每一行找到匹配的行。如果没有匹配的行,它会在结果集中保留PERSON行,并在PERSON_VACCINATION表中显示所有列的NULL值。
如果您正在寻找他们没有的人员和疫苗清单,那么@ MT0的答案是正确的。您需要创建一个包含PERSON和VACCINATION(交叉连接)的所有可能组合的结果集,然后检查PERSON_VACCINATION中实际存在哪些组合。任何不存在的条目都是您缺少的疫苗接种。