简体   繁体   中英

Excluding column from MySQL SELECT distinct query with UNION across tables

I have an SQL database with several tables of patient data. Every table has one column in common, an ID number representing each patient. There is significant overlap between the tables, ie the same patient ID number often appears on multiple tables. What I would like to do is SELECT all distinct patient ID numbers that do not appear on one specific table.

You can use UNION and NOT IN like this:

select id
from (
    select id from table1
    union
    select id from table2
    union
    select id from table3
    ...
) t where id not in (
    select id from sometable
);

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