两张一模一样的表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'
请大家帮帮忙!
或者怎么判断一个数据存不存在于这个表内?
不行。。。查不出来
追答select count(*) from a where id='10289'
0就是空 有數值就表示有多少數據
你把你的表跟你寫的那個都貼出來看看
怎麼會不行呢?最好是把表內的數據也貼出來看看
您这样是把两张表合起来了,但是碰到比如两张表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测试通过,你执行下试试就知道了
我试了下您写的,不行。。。。
追答我知道了 你肯定是name在a表里面是空但不是null 你把case when name is null 换成
case when name =‘’来试一下
还是不行。。。 一样
追答那就奇怪了 你把id='10289'在a,b两个表的查询结果给我发一下截图我看看。