存在返回所有行的位置

时间:2012-07-24 01:56:19

标签: sql

我的where exists条款不起作用。我错过了什么微不足道的事情?

select * from patient as p
where exists
(
    select p.patientid, count(*) from tblclaims as c 
    inner join patient as p on p.patientid=c.patientid
    and p.admissiondate = c.admissiondate
    and p.dischargedate = c.dischargedate
    group by p.patientid
    having count(*)>500
)

患者和tblclaims通过三字段复合键连接在一起,如您在查询中所见。

3 个答案:

答案 0 :(得分:2)

count(*) from tblclaims as c是不必要的,可能会抛弃查询。

此外,您没有WHERE条款加入patient p条款{/ 1}}。

更不用说你在主查询和exists子句中使用p作为别名,这只是令人困惑。

您可能需要以下内容:

exists

答案 1 :(得分:1)

您根本不需要在子查询中使用内部联接;这实际上是你额外结果的原因。您应该在外部查询中引用“p”。

select * from patient as p
where exists
(
    select 1 from tblclaims as c 
    where p.patientid = c.patientid
       and p.admissiondate = c.admissiondate
       and p.dischargedate = c.dischargedate
    group by c.patientid
    having count(*)>500
)

答案 2 :(得分:0)

我不太喜欢存在。也许你可以使用其他功能。试试这个:

select * from patient as p
where patientid IN
(
    select p.patientid from tblclaims as c 
    inner join patient as p on p.patientid=c.patientid
    and p.admissiondate = c.admissiondate
    and p.dischargedate = c.dischargedate
    group by p.patientid
    having count(*)>500
)