我有两个表使用相同的复合键,我想用左连接加入它们。我的第一个查询是否以正确的方式执行此操作,或者第二次加入对抗B,因为在我的第二个示例中更好/更高效?我还应该提一下,这些表存在于数据库链接的两侧,所以我认为较少的连接会更好......
表A:
key1 | key2 | field
--------------------
1 | 1 | frog
1 | 2 | fish
3 | 2 | erik
表B:
key1 | key2 | otherField
---------------------------
1 | 1 | "three times"
1 | 3 | "rarely"
2 | 2 | "once"
期望的结果:
key1 | key2 | field | otherField
---------------------------------
1 | 1 | frog | "three times"
1 | 2 | fish | null
3 | 2 | erik | null
方法1:
select *
from A
left join B on (A.key1 = B.key1)
where (B.key2 = A.key2 or (B.key1 is null and B.key2 is null));
方法2:
select *
from A
left join B b1 on (A.key1 = b1.key1)
left join B b2 on (A.key2 = b2.key2)
答案 0 :(得分:0)
只需在两个键上保持联接:
SELECT A.key1, A.key2, A.field, B.otherfield
FROM A LEFT JOIN B
ON (A.key1 = B.key1)
AND (A.key2 = B.key2);