首页 新闻 会员 周边

这个sql语句要咋写

0
悬赏园豆:10 [已解决问题] 解决于 2013-08-01 17:29

 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语句要咋写啊?

橙色の橙子的主页 橙色の橙子 | 初学一级 | 园豆:193
提问于:2013-07-31 13:30
< >
分享
最佳答案
0

 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

收获园豆:4
Eddiew | 菜鸟二级 |园豆:286 | 2013-07-31 13:42

请将union all 换成 union

Eddiew | 园豆:286 (菜鸟二级) | 2013-07-31 13:45
其他回答(2)
0

存储过程

迅捷网络[来送福利] | 园豆:576 (小虾三级) | 2013-07-31 14:45
0

数据不大,你用子查询吧~

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
收获园豆:6
幻天芒 | 园豆:37175 (高人七级) | 2013-07-31 15:37

谢谢你的回答!真实的情况是数据量比较大呢,问题里面我描述的比较简单。。数据量大的话,用哪个比较好哇?

支持(0) 反对(0) 橙色の橙子 | 园豆:193 (初学一级) | 2013-08-01 14:49

@橙色の橙子: 数据大,推荐用连接(带join这种)...你可以实现我发的那条语句,呵呵~

支持(0) 反对(0) 幻天芒 | 园豆:37175 (高人七级) | 2013-08-01 14:53

@幻天芒: 我是想用你这个语句。

可是我只想输出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列啊?

支持(0) 反对(0) 橙色の橙子 | 园豆:193 (初学一级) | 2013-08-01 15:29

@橙色の橙子: 如果你只要3列的话,你最好采用1楼的方式~

支持(0) 反对(0) 幻天芒 | 园豆:37175 (高人七级) | 2013-08-01 17:07

@幻天芒: 好的,非常感谢!!

支持(0) 反对(0) 橙色の橙子 | 园豆:193 (初学一级) | 2013-08-01 17:28
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册