select distinct o.type,t1.name,t2.name from order o with(nolock)
left join table1 t1 on t1.orderid=o.id
left join table2 t2 on t2.orderid=o.id
我想实现,如果o.type等1就left join table1,否则的话就left join table2
用一个sql语句要咋写啊?
select distinct o.type,t1.name from order o with(nolock)
left join table1 t1 on t1.orderid=o.id where o.type = 1
union all
select distinct o.type,t2.name from order o with(nolock)
left join table2 t2 on t2.orderid=o.id where o.type <>1
请将union all 换成 union
存储过程
数据不大,你用子查询吧~
1楼的方案,还需要行列转换,才能达到你t1.name ,t2.name同时存在~
你还可以试试:
select distinct o.type,t1.name,t2.name from order o with(nolock) left join table1 t1 on t1.orderid=o.id and o.type=1 left join table2 t2 on t2.orderid=o.id and o.type<>1
谢谢你的回答!真实的情况是数据量比较大呢,问题里面我描述的比较简单。。数据量大的话,用哪个比较好哇?
@橙色の橙子: 数据大,推荐用连接(带join这种)...你可以实现我发的那条语句,呵呵~
@幻天芒: 我是想用你这个语句。
可是我只想输出TransactionID,PrepayType,PaymentCatalog这要怎么写呢
select distinct t1.TransactionID,t1.PrepayType,t1.PaymentCatalog,
t2.ExternalNo as TransactionID,t2.PaymentWay as PrepayType,t2.PaymentCatalog
from order o with(nolock)
left join table1 t1 on t1.orderid=o.id and o.type=1
left join table2 t2 on t2.orderid=o.id and o.type<>1
我这样写输出的是6列,是不是只有union才能输出3列啊?
@橙色の橙子: 如果你只要3列的话,你最好采用1楼的方式~
@幻天芒: 好的,非常感谢!!