有两个表,
DoctorSeesPatient: (D1,P1),(D1,P2),(D2,P1),(D3,P1),(D3,P2),(D3,P3),(D4,P2),(D5,P1)
DoctorWorksAt: (D1,H1),(D2,H1),(D3,H1),(D4,H2),(D5,H3)现在想查出表中,搜出病人与医院(病人访问过医院里所有医生)结果应该如下
Result=(P1,H1),(P2,H2),(P1,H3)可是为什么我的语句不能正常运行呢...会有多余的数据create or replace view nq12_v1(patient,doctor,hospital) as
select s.patient, w.doctor, w.hospital from nq12_DoctorSeesPatient s, nq12_DoctorWorksAt w
where s.doctor = w.doctor
order by s.patient, w.hospital
;select distinct v.patient, v.hospital 
from nq12_v1 v
where NOT EXISTS(
(select distinct doctor from nq12_DoctorSeesPatient
where patient = v.patient
and doctor in(
select doctor from nq12_DoctorWorksAt
where hospital = v.hospital
)
)
minus
(select distinct doctor from nq12_DoctorWorksAt
where hospital = v.hospital
)
)
;

解决方案 »

  1.   

    select a.Patient,a.Hospital from 
    (select Patient,Hospital,count(*) as  DoctorNum 
    from nq12_v1 
    group by Patient,Hospital) a ,
    (select Hospital,count(*) as DoctorNum 
    from nq12_DoctorWorksAt
    group by Hospital) b
    where a.Hospital = b.Hospital
    and a.DoctorNum = b.DoctorNum ;
      

  2.   

    请测试这个,不需要改你的视图。
    SELECT DISTINCT v.patient, v.hospital
               FROM nq12_v1 v
              WHERE NOT EXISTS (
                       (SELECT doctor
                          FROM doctorworksat w
                         WHERE NOT EXISTS (
                                  SELECT doctor
                                    FROM doctorseespatient s
                                   WHERE s.doctor = w.doctor
                                     AND s.patient = v.patient)
                           AND w.hospital = v.hospital))