Postgresql Postgres:当每个表都可以为空时,如何连接表?
我有三张桌子。我对这三张表进行数学运算Postgresql Postgres:当每个表都可以为空时,如何连接表?,postgresql,Postgresql,我有三张桌子。我对这三张表进行数学运算 SELECT table_1.a + table_2.a + table_3.a FROM table_1 LEFT JOIN table_2 ON table_2.user_id = table_1.user_id LEFT JOIN table_3 ON table_3.user_id = table_1.user_id WHERE table_1.user_id = ? 但此查询中的每个表都可以为空 如何修复以正确处理空表 谢谢。示例: SELEC
SELECT table_1.a + table_2.a + table_3.a
FROM table_1
LEFT JOIN table_2 ON table_2.user_id = table_1.user_id
LEFT JOIN table_3 ON table_3.user_id = table_1.user_id
WHERE table_1.user_id = ?
但此查询中的每个表都可以为空
如何修复以正确处理空表
谢谢。示例:
SELECT * FROM table_1.a T1
LEFT JOIN table_2 T2 ON T1.user_Id = T2.FK
FK是第二个表上的外键。左连接将返回表1中的所有行,即使它们在表2中不存在。一种简单的方法是对包含目标id的行进行
左连接。
然后(如果需要)使用coalesce()
WITH target AS (SELECT ? AS user_id)
SELECT coalesce(table_1.a,0)
+ coalesce(table_2.a,0)
+ coalesce(table_3.a,0) AS sum_a
FROM target
LEFT JOIN table_1 ON target.user_id = table_1.user_id
LEFT JOIN table_2 ON target.user_id = table_2.user_id
LEFT JOIN table_3 ON target.user_id = table_3.user_id
;
您也可以从users\u表开始。user\u id
或类似的一些,其中user\u id
是主键,并且您知道user\u id必须存在(您可能在这里有FK关系?)。并使用WHERE
子句进行过滤
SELECT coalesce(table_1.a,0)
+ coalesce(table_2.a,0)
+ coalesce(table_3.a,0) AS sum_a
FROM user_table u
LEFT JOIN table_1 ON u.user_id = table_1.user_id
LEFT JOIN table_2 ON u.user_id = table_2.user_id
LEFT JOIN table_3 ON u.user_id = table_3.user_id
WHERE u.user_id = ?
;
使用full join
?@a_horse\u with_no_name:由于任何表都可以为空,因此ON
和WHERE
子句的条件都会变得很长。我知道任何表都可能没有user\u id
的行。问题没有提到您假设的外键关系。