SQL-左连接表自身

问题描述 投票:0回答:1

简而言之,要保留联接表本身,但仅保留ID为1或2的行

表格:

id f1
1  a
1  b 
2  a
3  a 

预期结果

1 2 a a
1 2 b null

不起作用:

select t1.id,t2.id, t1.f1,t2.f1
from table t1
left join table t2 on t1.f1 = t2.f1 and t1.id = 1 and t2.id = 2

任何想法?

sql join
1个回答
0
投票

此结构有点奇怪,但是您需要过滤where中的第一个表:

select t1.id, t2.id, t1.f1, t2.f1
from table t1 left join
     table t2
     on t1.f1 = t2.f1 and t2.id = 2
where t1.id = 1 ;

left join的一般规则是,第一个表上的条件在where子句中。第二个表上的条件放在on子句中。

© www.soinside.com 2019 - 2024. All rights reserved.