sql语句判断一张表的某字段为空,然后查找另外一张表的数据,怎么写?

两张一模一样的表a和b,字段id和name。
现在要求查a表里面的数据,如果a里面没有此数据,则查b表里面的数据,这个怎么实现?
我写了一个查name的,貌似不行:
select case when id is null then (select name from b where id='10289')
else (select name from a where id='10289') end
from a
where id='10289'

请大家帮帮忙!
或者怎么判断一个数据存不存在于这个表内?

第1个回答  2011-08-16
楼上那个不行,应该是A没有再找B 而不是连接2个表一起找
楼主你的代码的问题出在when id is null 你都输入ID=10289了
id怎麼会空?
应该是
select case
when A.name is null then
B.name
else
A.name
end name
from (select name from a where id = '10289') A,(select name from b where id = '10289') B追问

不行。。。查不出来

追答

select count(*) from a where id='10289'
0就是空 有數值就表示有多少數據
你把你的表跟你寫的那個都貼出來看看
怎麼會不行呢?最好是把表內的數據也貼出來看看

第2个回答  推荐于2018-03-14
select top 1 name from(
select name, 1 as xh from a where id=10289
union all
select name, 2 as xh from b where id=10289
) order by xh追问

您这样是把两张表合起来了,但是碰到比如两张表id都有10289的,就会出错了,我的意思如果a里面有10289的,就直接查出来,因为B里面也有可能有10289

追答

最外面那个select top 1 name 就是选择的,如果只有一个,那就是那一个,如果两个表都有10289,那么a表的序号是1,b表的序号是2,select top 1的话,根据序号排序,就是取a的了
select top 1 name from(
select name, 1 as xh from a where id=10289
union all
select name, 2 as xh from b where id=10289
)tmp order by xh
加了个tmp,sql2005测试通过,你执行下试试就知道了

本回答被提问者和网友采纳
第3个回答  2011-08-16
select t.id,t.name from
( select id,name from a union select id,name from b) t
group by t.id,t.name

这样查询每个记录只会存在一条,这样查询出来的是最全的,不过不知道那个是A 表那个是B表的,它查询出来的是A.B的汇总,但是是唯一的
第4个回答  2011-08-16
select
case
when a.id is not null then a.name
else b.name end
from
a FULL JOIN b ON (a.id = b.id )
where
a.id='10289' OR b.id='10289'
第5个回答  2011-08-16
你的case when 后面的字段错了 应该是name 下面的才是正确的

select
case when name is null then (select name from b where id='10289')
else (select name from a where id='10289') end
from a
where id='10289'追问

我试了下您写的,不行。。。。

追答

我知道了 你肯定是name在a表里面是空但不是null 你把case when name is null 换成
case when name =‘’来试一下

追问

还是不行。。。 一样

追答

那就奇怪了 你把id='10289'在a,b两个表的查询结果给我发一下截图我看看。

相似回答