【发布时间】:2016-05-24 08:51:35
【问题描述】:
我有这张桌子:
name code value
--------------------------
| john | 0001 | 1 |
| mary | 0001 | 2 |
| mary | 0002 | 3 |
我想要实现的结果集如下所示:
name code value
--------------------------
| john | 0001 | 1 |
| john | 0002 | NULL |
| mary | 0001 | 2 |
| mary | 0002 | 3 |
换句话说,我希望结果包含一行,其中code 的0002 为john,而表中缺少该行。
我原以为这样的事情会让我更接近:
with x as (select distinct code from t)
select * from t left join x on x.code = t.code
但我得到的基本上是同一张桌子:
name code value value1
-------------------------- --------
| john | 0001 | 1 | 1 |
| mary | 0001 | 2 | 2 |
| mary | 0002 | 3 | 3 |
一些额外的想法使我得出结论,我的解决方案无论如何都不可能工作,因为name 也可能是NULL,我真的需要它出现。
我被难住了,这看起来比实际上容易。
谁能解释一下?
【问题讨论】:
-
使其成为右连接(或在第二行交换 x 和 t :
select * from x left joint t on x.code = t.code) -
@joop 我以前试过,但没用。
标签: sql postgresql join distinct postgresql-9.3