在单个查询中返回多个表ID以查看它们是否存在?

时间:2016-10-30 10:29:49

标签: mysql sql

我从多个表中获得了一些主键值。我想在一个查询中检查它们是否存在。我试过这个查询。

        select BR.id, AREA.id, HOUSE.id, TABLET.id, REGION.id, AC.id, SUPERVISOR.id 
        from BR, AREA, HOUSE, TABLET, REGION, AC, SUPERVISOR 
        where BR.id in (851) or AREA.id in (91) or HOUSE.id in (566) or TABLET.id in (896, 897, 898) or 
        REGION.id in (89) or AC.id in (775) or SUPERVISOR.id in (895) 
        GROUP BY BR.id, AREA.id, HOUSE.id, TABLET.id, REGION.id, AC.id, SUPERVISOR.id

但它会返回大量结果并且效率低下。有没有办法在一个有效运行的查询中检查多个表的多个id的存在?

2 个答案:

答案 0 :(得分:1)

使用UNION声明

select 'BR' as table_name, id from BR where id in (851)
union all
select 'AREA' as table_name, id from AREA where id in (91)
union all
select 'HOUSE' as table_name, id from HOUSE where id in (566)
union all
select 'TABLET' as table_name, id from TABLET where id in (896, 897, 898)
union all
select 'REGION' as table_name, id from REGION where id in (89)
union all
select 'AC' as table_name, id from AC where id in (775) 
union all
select 'SUPERVISOR' as table_name, id from SUPERVISOR where id in (895)

结果将类似于

| table_name | id  |
|------------|-----|
| BR         | 851 |
| HOUSE      | 566 |
| TABLET     | 896 |
| TABLET     | 897 |

答案 1 :(得分:0)

尝试使用组合了两个SELECT语句的EXCEPT子句,并返回第一个SELECT语句中未被第二个SELECT语句返回的行