如何检查多个表中是否存在“名称”?

时间:2019-01-05 10:28:19

标签: mysql sql

如果表1中的所有“名称”都存在于表2 [具有相同名称的多行]和表3中,我愿意得到结果

已经检查了这些:
1. Check if data exists across multiple tables
2. How to check if a given data exists in multiple tables (all of which has the same column)?

select idprov, (select a.provinsi from mst_province a where a.id_tbl_mst_prov = c.idprov ) as provinsi, namasite as namasite, count(namasite) as count from form_kuesioner_pengelola c 
union
select idprov, (select a.provinsi from mst_province a where a.id_tbl_mst_prov = c.idprov ) as provinsi, namasite as namasite, count(namasite) as count from form_kuesioner_manfaat c group by namasite 
union
select idprov, (select a.provinsi from mst_province a where a.id_tbl_mst_prov = c.idprov ) as provinsi, namalokasi as namasite, count(namalokasi) as count from form_kuesioner_surveyor c

因此,上面代码的结果为我提供了表1中存在的所有“名称”,包括其他表中不存在的“名称”。

我希望我的结果像

 table
    'name1' = 1 (exist) from form_kuesioner_pengelola  
    'name1' = 0 (not exist) from form_kuesioner_manfaat  
    'name1' = 0 (not exist) from form_kuesioner_surveyor

我知道我离“附近”不远,您能启发我吗?

谢谢

1 个答案:

答案 0 :(得分:2)

使用NOT EXISTS获取一个表中存在的名称,而其他表则不存在:

select *
from form_kuesioner_pengelola p
where name = 'xyz'
  and not exists (select * from form_kuesioner_manfaat m where m.name = p.name)
  and not exists (select * from form_kuesioner_surveyor s where s.name = p.name)
order by name;

(如果nameform_kuesioner_manfaat中的form_kuesioner_surveyor从不为空,则您甚至可以将NOT EXISTS子句替换为更简单的NOT IN子句。)

更新:这是显示名称出现在哪些表中的方法。

select
  exists (select * from form_kuesioner_pengelola where name = 'xyz') as in_pengelola,
  exists (select * from form_kuesioner_manfaat where name = 'xyz') as in_manfaat,
  exists (select * from form_kuesioner_surveyor where name = 'xyz') as in_surveyor;

更新:这是一个查询,用于检查表中所有名称是否存在。这有点笨拙,因为MySQL仍不支持完全外部联接。

select
  names.name,
  count(p.name) as in pengelola,
  count(m.name) as in in_manfaat,
  count(s.name) as in in_surveyor
from
(
    select name from form_kuesioner_pengelola
    union
    select name from form_kuesioner_manfaat
    union
    select name from form_kuesioner_surveyor
) names
left join form_kuesioner_pengelola p on p.name = names.name
left join form_kuesioner_manfaat m on m.name = names.name
left join form_kuesioner_surveyor s on s.name = names.name
group by names.name
group by names.name;