简体   繁体   中英

SQL query to get records that match ALL the criteria

I need to write a SQL query to get the patients that have stayed in ALL the hospitals of the city where they live. In one city there may be several hospitals of course.

So for example, if the patient 'xxx' who lives in Washington has been in a hospital, I need to list him only if he's been in all the hospitals of Washington and no less.

This is the structure of the tables:

table patient

    patientID
    patientCity

table hospital

    hospitalCode
    hospitalCity

table hospital_stay

    hospitalCode
    patientID
    cityStay

What's the most efficient way to do this for MySQL? Thank you!

This query should work :

Select p.patientID
     , p.patientCity 
  from patient p
    inner join hospital h on h.hospitalCity = p.patientCity
    inner join hospital_stay hs on hs.hospitalCode = h.hospitalCode
 --where hs.cityStay = 1
group by p.patientID, p.patientCity 
having count(*) = (select count(*) from hospital
                    where hospitalCity = p.patientCity);

Remove the comment if cityStay is kind of a flag that says that the patient went to the hospital.

Unfortunately, MySQL can't order before grouping, so I had to use subquery to order the result correctly before grouping it.

Have fun :)

SELECT * FROM (
    SELECT 
        p.patientID,
        hs.hospitalCode
    FROM
        patient p
        INNER JOIN hospital h ON (p.patientCity = h.hospitalCity)
        LEFT JOIN hospital_stay hs ON (p.patientID = hs.patientID AND h.hospitalCode = hs.hospitalCode)
    ORDER BY 2
) AS tmp_table
GROUP BY 1
HAVING NOT ISNULL(hospitalCode)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM