在mysql中使用if else连接语句

时间:2013-10-23 05:25:50

标签: mysql

让我直截了当地说明问题。这是我的sql小提琴sql fiddle

现在我的要求是在以下条件下使用带有表A的join语句从表B或表C中检索名称列

If result is present in table B retrieve name from table B and ignore table C
else retrieve name field from table c

基本上我需要以下结果

1 AB name1
2 BC name2
3 CD name3

3 个答案:

答案 0 :(得分:2)

select id,A.column1,D.name from A left join 
(select * from B union select * from C) as D on A.column1=D.column1

答案 1 :(得分:0)

select * from B
UNION 
select * from C where column1 not in (select column1 from B)
order by name

SQL小提琴链接:http://sqlfiddle.com/#!2/5f4f4/16

答案 2 :(得分:0)

如上所述,您不需要执行if语句。试试以下内容:

 select A.id, A.column1 from A left join B on A.column1 = B.column1 
 left join C on C.column1 = A.column1;

SQL Fiddle