我需要离开外部联接两个表,但我也总是想拥有“不匹配”行。示例:
left table:
|--------------|
| *c1* | *key* |
|--------------|
| a1 | a |
|------|-------|
| b1 | b |
|--------------|
right table:
|--------------|
| *c2* | *key* |
|--------------|
| a2 | a |
|--------------|
expected result, joined by *key* column:
|-------------|
| *c1* | *c2* |
|-------------|
| a1 | a2 |
|------|------|
| a1 | null | <- this row is needed
|------|------|
| b1 | null | <- in case there is no match, only one "value, null" row is needed
|-------------|
实现它的最佳方法是什么?最好不使用distinct
或union
。
我认为您想要inner join
和union all
:
select l.c1, r.c2
from left l join
right r
on l.key = r.key
union all
select l.c1, null
from left l;