我怎样才能加入两个结果

How can I join two results

我购买了 3 table,air_transfers 和 sea_transfers。 我在db fiddle中制作了示例代码。我的问题是第 6 段,我没有任何海运,我得到 null 作为 id,那是因为我正在使用来自海运的 id。我应该怎么做才能解决这个问题?

购买table:

CREATE TABLE purchase
(
id SERIAL PRIMARY KEY,
date DATE NOT NULL
)

空运table:

CREATE TABLE air_transfers
(
id SERIAL PRIMARY KEY,
purchase_id INTEGER NOT NULL REFERENCES purchase(id),
units INTEGER NOT NULL
)

海运 table:

CREATE TABLE sea_transfers
(
id SERIAL PRIMARY KEY,
purchase_id INTEGER NOT NULL REFERENCES purchase(id),
units INTEGER NOT NULL
)

我的外连接:

WITH sea_transfers AS (
SELECT purchase_id, SUM(units) AS units
FROM sea_transfers
GROUP BY purchase_id
),
air_transfers AS (
SELECT purchase_id, SUM(units) AS units
FROM air_transfers
GROUP BY purchase_id
)
SELECT st.purchase_id, (COALESCE(st.units,0) + COALESCE(at.units,0)) AS units
FROM sea_transfers AS st
FULL OUTER JOIN air_transfers AS at
ON st.purchase_id = at.purchase_id

如果我的海运是空的,我会得到这个结果:

我认为您正在寻找 UNION ALL 而不是 FULL OUTER JOIN,因为 UNION ALL 将合并两个结果 air_transferssea_transfers 表,您将得到来自两个表的所有 purchase_idunits 值。

SELECT  purchase_id, SUM(units) AS units
FROM (
   SELECT purchase_id,units FROM air_transfers
   UNION ALL
   SELECT purchase_id,units FROM sea_transfers
) t1
GROUP BY purchase_id

你可以做到

SELECT COALESCE(st.purchase_id, at.purchase_id) as purchase_id

Fiddle