我如何展示" 1"而不是NULL?
这是我的表格:
|policies|
|id| |policy|
1 abc
2 def
|insurances|
|id| |policy_id| |money|
1 1 1000
2 1 2000
3 2 3000
4 2 4000
5 1 1000
这里是查询:
select sum(money) as cash from insurances i
INNER JOIN policies p ON p.id = i.policy_id
WHERE i.policy_id = 3
Group by i.policy_id
在这种情况下,当policy_id = 3时,它显示NULL:
|cash|
NULL
我想表明:
|cash|
1
我也试过,但没有工作:
select sum(money)+1 as cash from insurances i
INNER JOIN policies p ON p.id = i.policy_id
WHERE i.policy_id = 3
Group by i.policy_id;
答案 0 :(得分:1)
SELECT COALESCE(sum(money), 1) as Cash
FROM (
SELECT policy_id, money
FROM
insurances i INNER JOIN policies p
ON p.id = i.policy_id
WHERE
i.policy_id = 1
) s
编辑或者您可以尝试使用这个小技巧:
SELECT COALESCE(MAX(cash), 1) FROM (
SELECT sum(money) AS cash
FROM insurances i
INNER JOIN policies p ON p.id = i.policy_id
WHERE i.policy_id = 3
GROUP BY i.policy_id
) s