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