如何使用EXISTS来实现业务条件

时间:2015-04-10 08:06:55

标签: sql-server

create table pat(id int primary key,name varchar(10),address varchar(10))

create table preds(id int primary key,ptext varchar(10),pat_id int foreign key references pat(id))

create table vists(id int primary key,reasn varchar(100),patid int foreign key references pat(id))

- 列出所有活跃的患者 - 如果访问表中至少有一条记录 - 至少1个记录

  1. - 如何使用该视图列出所有独特患者。

  2. select * from pat where exists(select id from vists v join pat p on v.id=p.patid 
            union 
            select id from preds pr join pat p on pr.patid=p.id
            )
    

2 个答案:

答案 0 :(得分:1)

我认为这会给你所需要的东西:

SELECT P.*
FROM PAT P
INNER JOIN (
    SELECT P.ID
    FROM PAT P
    INNER JOIN VISITS V ON P.id = V.patid
    INNER JOIN PREDS PR ON P.id = PR.pat_id
    GROUP BY P.ID
    HAVING (
            COUNT(V.iD) > 1
            AND COUNT(PR.ID) > 1
            )
    ) Patients ON P.ID = Patients.ID

下次我建议你发布一个包含表结构SQLFiddle的链接,其中包含一些示例数据,以便我们可以更轻松/更快地测试和提供解决方案。

实施EXISTS的版本是:

SELECT *
FROM PAT P1
WHERE EXISTS (
    SELECT 1
    FROM PAT P
        INNER JOIN VISITS V ON P.id = V.patid
            AND P.id = P1.id
        INNER JOIN PREDS PR ON P.id = PR.pat_id
    GROUP BY P.ID
    HAVING (COUNT(V.iD) > 1 AND COUNT(PR.ID) > 1))

答案 1 :(得分:0)

聚合是一个非常繁重的操作,因为它使用排序。最好使用EXISTS,但改为使用JOIN:

SELECT
    *
FROM
    pat p
WHERE
    EXISTS ( SELECT
                *
             FROM
                vists v
                JOIN preds pr ON pr.pat_id = v.patid
                                 AND pr.pat_id = p.id );