注意是sqlite的,没有地方问,就来这了
有两个字段一样的表,table1是主表,table2是附表(别名表)
/*表1*/
drop table if exists table1;
create table table1(id int
,name varchar(32)
);
/*表2*/
drop table if exists table2;
create table table2(id int
,name varchar(32)
);
insert into table1 values(1, '张三');
insert into table1 values(2, '李四');
insert into table2 values(1, '非张三');
要求写一个SQL语句,当table2有记录时,显示table2的name,否则显示table1的name
即显示结果是:
id, name
1 非张三
2 李四
我尝试这么写,达不到效果,请教各位大神了
select
id, case name2 when null then name1 else name2 end as name
from
(select a.id,a.name as name1,b.name as name2 from table1 a left join table2 b on a.id=b.id);
------解决方案--------------------
Oracle的写法:
select t1.id,
nvl((select name from table2 where id = t1.id),
(select name from table1 where id = t1.id))
from (select id from table1 union select id from table2) t1
------解决方案--------------------
如果数据是
insert into table1 values(1, '张三');
insert into table1 values(2, '李四');
insert into table2 values(1, '非张三');
那么你的SQL语句应该可以,除非T2有记录,而T1中没有,那就要要用UNION ALL了
select a.*,coalesce(c.name,b.name)
from (
select id from table1 union select id from table2) a
left join t1 b on a.id=b.id
left join t2 c on a.id=c.id