【问题标题】:Basic SQL Query Help (Not Exists)基本 SQL 查询帮助(不存在)
【发布时间】:2015-12-11 04:02:01
【问题描述】:

我有 3 张表 Doctor、Patient 和 Visit。

Doctor Table 包含 DoctorID、Name 和 City。

Patient Table 包含 PatientID、Name 和 City。

访问表有 DoctorID、PatientID、NumVisits。

我正在尝试检索某个城市(比方说纽约)的患者未曾就诊的所有医生。

我在编写查询方面非常陌生,但我似乎无法让它发挥作用。

我的代码:

SELECT DoctorId,
   Doctor.Name
FROM Visit
JOIN Doctor using(DoctorID)
JOIN Patient using(PatientID)
WHERE NOT EXISTS
    (SELECT DoctorId,
            Doctor.Name
     FROM Visit
     JOIN Doctor using(DoctorID)
     JOIN Patient using(PatientID)
     WHERE Patient.City = 'New York');

有人可以向我解释我做错了什么吗?也许我的整个方法都不正确。

【问题讨论】:

  • 您绝对不需要 6 个查询来完成此操作!退后一步从不同的角度考虑会有所帮助,一个很好的经验法则是,您应该 never 执行比查询中涉及的表更多的连接!!!

标签: sql not-exists


【解决方案1】:

您应该将子查询与主查询连接起来。 现在,在您的子查询中,您选择了来自纽约的所有医生,当然您至少有一位。 这就是为什么WHERE NOT EXISTS (1 or more rows) 永远不会是真的。 试试这样的

SELECT DoctorId,
   Doctor.Name
FROM Visit
JOIN Doctor using(DoctorID)
JOIN Patient using(PatientID)
WHERE NOT EXISTS
    (SELECT *
     FROM Visit
     JOIN Patient using(PatientID)
     WHERE Patient.City = 'New York')
     and Visit.Doctorid=Doctor.DoctorID -- Doctor.DoctorID from main query
;

并且(感谢@Brad): 由于外部查询中未使用 Patient,因此您可以删除针对 Patient 和 Visit 的第一个 JOIN。事实上,您应该在外部查询中删除针对 Patient 和 Visit 的连接,否则您将错过没有患者的医生的记录。 结果将是

SELECT DoctorId,
   Doctor.Name
FROM Doctor 
WHERE NOT EXISTS
    (SELECT *
     FROM Visit
     JOIN Patient using(PatientID)
     WHERE Patient.City = 'New York')
     and Visit.Doctorid=Doctor.DoctorID -- Doctor.DoctorID from main query
;

【讨论】:

  • 由于外部查询中没有使用 Patient,因此您可以删除第一个 JOINPatientVisit。实际上,您应该在外部查询中删除针对 Patient 和 Visit 的联接,否则您将错过没有患者的医生的记录。
  • 谢谢@Brad!没想到
【解决方案2】:
SELECT DISTINCT D.DOCTORID
FROM Visit V
       INNER JOIN PATIENT P ON P.PATIENTID = V.PATIENTID AND P.CITY='NEWYORK'
       RIGHT JOIN DOCTOR D ON D.DOCTORID = V.DOCTORID
WHERE P.PATIENTID IS NULL

在这里提琴:http://sqlfiddle.com/#!3/0e194/1

【讨论】:

    【解决方案3】:

    你可以这样做:

    SELECT DoctorId, Doctor.Name
    From Doctor 
    Where DoctorId NOT IN (Select DoctorId From Visit
                           Where  PatientID IN (Select  PatientID From Patient 
                                                    Where  City = 'New York'))
    

    这样你在最里面的选择中选择指定城市的病人,然后你把那些病人访问过的DoctorId,最后选择不在他们中间的医生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-20
      • 1970-01-01
      • 2021-07-14
      • 2016-08-10
      相关资源
      最近更新 更多