SQL查询记录是否在另一个表中存在


1、需求

create table ta(id int);
create table tb(id int);
insert into ta values(1);
insert into ta values(2);
insert into ta values(3);

insert into tb values(1);
insert into tb values(1); --假如tb表中记录可以重复

select * from ta ;


想知道ta的每条记录是否在tb表中存在。

比如查询结果为:0为不存在。
id    isexists
1      1
2      0
3      0

2、实现

(1)比较懒的实现方式

select a.id, nvl(b.id,0) 
from ta a
  left join (select distinct id from tb) b
    on a.id = b.id

(2)标量子查询方式

select id,(select decode(count(*),0,0,1) from tb where ta.id=tb.id and rownum=1) isexists
from ta;

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM