我有两个表:我的数据库中的tire_life和transaction。
当子查询返回值时,它工作正常,但是当没有返回任何行时,它不会更新tire_life表。
这就是我正在运行的查询。
UPDATE tire_life as life SET covered_distance = initial_durability + transactions.durability
FROM (SELECT tire_life_id, SUM(tire_covered_distance) as durability
FROM transaction WHERE tire_life_id = 24 AND deleted_at IS NULL
GROUP BY (tire_life_id)) as transactions
WHERE life.id = 24
我试图使用COALESCE()函数,但根本没有成功。
答案 0 :(得分:1)
只有当子查询返回单列时,才能使用coalesce()
作为子查询。由于您不在子查询外使用tire_life_id
,因此可以跳过它:
UPDATE tire_life as life
SET covered_distance = initial_durability + transactions.durability
FROM (
SELECT coalesce(
(
SELECT SUM(tire_covered_distance)
FROM transaction
WHERE tire_life_id = 24 AND deleted_at IS NULL
GROUP BY (tire_life_id)
), 0) as durability
) as transactions
WHERE life.id = 24;
如果子查询没有返回任何行,我想你希望得到0为durability
。