带有额外条件的sql join

时间:2017-01-26 22:54:37

标签: sql-server database

T1:

items, id, [...]
a      12       
b      21
c      34
d      45
e      52

T2:

items order 
a      1
b      2
others 3

期望的结果:

items, id, [...], order
a      12         1
b      21         2
c      34         3
d      45         3
e      52         3

我基本上想要一切不匹配的' a'' b'来获得'其他'的排序。但是对于内部联接,我不知道该怎么做,我只能加入,如果有匹配,我是否必须使用子查询来做这样的事情?

Select t1.items, t1.id, t2.order
t1
inner join 
t2
On t1.items = t.items

2 个答案:

答案 0 :(得分:2)

您可以像这样使用join

select t1.*, coalesce(t2.order, t2other.order) as ordering
from t1 left join
     t2
     on t1.items = t2.items left join
     t2 t2other
     on t2other.items = 'other';

答案 1 :(得分:0)

假设没有t1.item = order你将获得NULL。

builder.RegisterType<PortalCodeProvider>().AsImplementedInterfaces().InstancePerRequest();
builder.RegisterType<MyContext>().InstancePerRequest();

或使用CASE声明:

select items, id, IsNull(t2.order, 3) order
from t1
     left join t2 on t1.items = t2.items;