mysql中if条件与leftjoin怎么连用?

小-文 2014-07-30 03:18:39
我在表A里,有个type字段,当type是1时左关联B表,当type是2时,左关联C表,怎么弄?
...全文
1854 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
卖水果的net 2014-07-31
  • 打赏
  • 举报
回复 1

-- 凑个人数,使用 case when 就可以判断一下
create table a(id int ,type int , name varchar(30) )
insert into a values (1,1,'aaa')
insert into a values (2,2,'bbb')
insert into a values (3,1,'ccc')
insert into a values (4,2,'ddd')

create table b(id int , b_m varchar(30))
insert into b values (1,'xxx')
insert into b values (2,'yyy')

create table c(id int , c_m varchar(30))
insert into c values(2,'bbbbbb')
insert into c values(3,'ccccccc')
insert into c values(4,'dddddddd')

select a.id , a.type ,a.name ,
case when a.id = 1 then b.b_m else c.c_m end as dc
from a 
left join b on a.id = b.id 
left join c on a.id = c.id 

ACMAIN_CHM 2014-07-30
  • 打赏
  • 举报
回复
select *
from A left join (
	select 1 as ktype,id,col1,col2,col3,coln from B
	union all
	select 2 as ktype,id,col1,col2,col3,coln from c
) t on a.type=t.ktype and a.id=t.id
业余草 2014-07-30
  • 打赏
  • 举报
回复
顶你,这个倒sql专区,会的人多

56,675

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧