【发布时间】:2021-02-26 01:40:18
【问题描述】:
我有 3 张桌子,一张用于医生、病人和约会,如下所示
create table Doctors
(
Did int identity primary key,
docName varchar (20),
specialization varchar (20),
salary decimal (8,2)
)
create table Patients
(
Pid int identity primary key,
fullName varchar (20)
)
create table Appointments
(
datey DATETIME,
pid int foreign key REFERENCES Patients(Pid),
did int foreign key REFERENCES Doctors(Did),
primary key (pid, did)
)
我正在尝试理解“获取已与所有患者预约的医生”的查询。这是查询:
SELECT D.docName
FROM Doctors D
WHERE NOT EXISTS (
(
SELECT P.Pid
FROM Patients P
)
EXCEPT
(
SELECT A.pid
FROM Appointments A
WHERE A.did = D.Did
)
)
我知道Where not Exists 之后的子查询部分正在查询所有当前没有医生预约的患者。我不明白的是,当它被提供给where NOT Exists 时,它会向我显示自从我使用 Visual Studio 代码中的一些数据运行子查询以来确实有预约的医生的姓名。查询结果为空。
那么where not exist 和一般查询在这种情况下是如何工作的呢?
谢谢。
【问题讨论】:
-
一般比较常见的写成两个嵌套的
NOT EXISTS,效果(和查询计划)是一样的,但是可能更容易阅读
标签: sql sql-server database relational-database