此查询中的 WHERE NOT EXISTS 如何工作?
How does WHERE NOT EXISTS in this query work?
我有 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
和一般查询究竟如何工作?
谢谢。
这个解释起来有点复杂。但我的想法是重新表述问题:
Get all doctors such that there is no patient that doesn't have an appointment with the doctor.
即使英语是您的母语,所有这些负面因素也会让问题难以理解。这是表达您想要的另一种方式:“获取与所有患者有过约会的医生”。
步骤如下:
- 第一个子查询获取所有患者。
- 第二个子查询获取特定医生的所有患者。
EXCEPT
获取尚未与医生预约的患者列表。
- 最后,如果有none,那么医生就已经约好了所有的病人
相比之下,另一种使用聚合的方法似乎不言自明:
SELECT D.did, D.docName
FROM Doctors D JOIN
Appointments A
ON A.did = D.did
GROUP BY D.did, D.docName
HAVING COUNT(DISTINCT A.pid) = (SELECT COUNT(*) FROM Patients);
我有 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
和一般查询究竟如何工作?
谢谢。
这个解释起来有点复杂。但我的想法是重新表述问题:
Get all doctors such that there is no patient that doesn't have an appointment with the doctor.
即使英语是您的母语,所有这些负面因素也会让问题难以理解。这是表达您想要的另一种方式:“获取与所有患者有过约会的医生”。
步骤如下:
- 第一个子查询获取所有患者。
- 第二个子查询获取特定医生的所有患者。
EXCEPT
获取尚未与医生预约的患者列表。- 最后,如果有none,那么医生就已经约好了所有的病人
相比之下,另一种使用聚合的方法似乎不言自明:
SELECT D.did, D.docName
FROM Doctors D JOIN
Appointments A
ON A.did = D.did
GROUP BY D.did, D.docName
HAVING COUNT(DISTINCT A.pid) = (SELECT COUNT(*) FROM Patients);