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;

 引自博客: https://www.shuzhiduo.com/A/nAJv6A0YJr/

posted @ 2023-03-20 16:56  moonsoft  阅读(182)  评论(0编辑  收藏  举报