注册 登录
编程论坛 SQL Server论坛

判断请教

ppppooiiuu 发布于 2017-03-08 17:04, 1251 次点击
假设有两个表,表1有一列,表2也有一列,如何判断表1的值是否有在表2
列   列  是否
a    b   否
b    c   是
c        是
d        否
1 回复
#2
mywisdom882017-03-09 10:03
if object_id('tempdb..#表1') is not null drop table #表1
create table #表1(列1 varchar(10),列2 varchar(10))
insert into #表1
select '101','201' union all
select '102','202' union all
select '103','203' union all
select '104','204' union all
select '105','205' union all
select '106','206'


if object_id('tempdb..#表2') is not null drop table #表2
create table #表2(列1 varchar(10),列2 varchar(10))
insert into #表2
select '109','209' union all
select '107','207' union all
select '105','205' union all
select '103','203' union all
select '101','201' union all
select '100','200'

--查表1在表2是否存在
select a.列1,a.列2,case when a.列1=b.列1 then '是' else '否' end as 是否 from #表1 a
left join #表2 b on a.列1=b.列1

--查表2在表1是否存在
select b.列1,b.列2,case when a.列1=b.列1 then '是' else '否' end as 是否 from #表2 b
left join #表1 a on a.列1=b.列1

--只查2个表都有的
select a.列1,a.列2,case when a.列1=b.列1 then '是' else '否' end as 是否 from #表1 a
inner join #表2 b on a.列1=b.列1


1