我試圖在postgresql數據庫上使用full outer join
來獲取缺失行具有空值的表的聯合。但是,它不適合我。完全外部聯接缺少值爲null
這裏是例子:
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 | <----
+---------------------------------+
偉大的,更新我的答案,以刪除不可能:) – jontro
這就是它。非常感謝。什麼是查詢! – James