sql - 带 null 的完整外连接缺失值

标签 sql postgresql outer-join

我正在尝试在 postgresql 数据库上使用完全外连接来获取缺失行具有空值的表的并集。但是,它对我不起作用。

示例如下:

create temp table nutrient_names (
    name text
);

insert into nutrient_names values
('fat'),
('sugar'),
('sodium'),
('total fat');

create temp table nutrients (
    food_id int,
    name text,
    quantity float8
);

insert into nutrients values
(1, 'fat', 0.3),
(1, 'sugar', 15),
(1, 'sodium', 10),
(1, 'total fat', 25),
(2, 'sugar', 10),
(2, 'sodium', 4);

这是输出:

select n.name, n.food_id, n.quantity from nutrient_names nn
full outer join nutrients n
on nn.name = n.name
order by n.food_id, n.name;

+---------------------------------+
|name           |food_id |quantity|
+---------------------------------+
|    'fat'      |1       |'0.3'   |
|    'sodium'   |1       |'10'    |
|    'sugar'    |1       |'15'    |
|    'total fat'|1       |'25'    |
|    'sodium'   |2       |'4'     |
|    'sugar'    |2       |'10'    |
+---------------------------------+

我想要什么:

+---------------------------------+
|name           |food_id |quantity|
+---------------------------------+
|    'fat'      |1       |'0.3'   |
|    'sodium'   |1       |'10'    |
|    'sugar'    |1       |'15'    |
|    'total fat'|1       |'25'    |
|    'fat'      |2       |null    | <----
|    'sodium'   |2       |'4'     |
|    'sugar'    |2       |'10'    |
|    'total fat'|2       |null    | <----
+---------------------------------+

最佳答案

FULL JOIN 看起来不适合这里。根据您的示例,您希望列出 nutritional_names 中的所有行,次数与您拥有的食物 ID 一样多。这通常通过CROSS JOIN来完成。

如果您没有包含食物 ID 列表的单独表,您可以即时构建它,然后加入其中:

WITH
CTE_IDs
AS
(
    SELECT DISTINCT
        food_id
    FROM nutrients
)
SELECT
    nutrient_names.name
    ,CTE_IDs.food_id
    ,nutrients.quantity
FROM
    CTE_IDs
    CROSS JOIN nutrient_names
    LEFT JOIN nutrients 
        ON  nutrients.name = nutrient_names.name
        AND nutrients.food_id = CTE_IDs.food_id
;

关于sql - 带 null 的完整外连接缺失值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760247/

相关文章:

python - 结合 np.equal 和 np.less 创建单个数据帧?

r - 如何将外部尺寸推广到n个尺寸?

SQL Server 2008 R2 Express : way to convert NULL's from Joins to zeros

SQL Server更新触发器: How to make it work

sql - 如果 PostgreSQL 中不存在数据,则获取值为零

eclipse - Eclipse 中的 JPA 项目问题 - 注释为@Entity : Table "xxx" cannot be resolved 的类中的错误

sql - 有 Node 对象关系映射包吗?

php - 如何检查两个日期之间是否已收取租金

postgresql - 从头开始为 Heroku 应用程序运行所有迁移

sql - 自连接与内部和外部连接查询