我有一个mysql查询:
select userid, sum(fees)
from table1
where userid in (
select distinct userid
from table2
where condition1 = 2
and condition2 =5
)
group by userid;
现在,它可以工作,但是如果sum(fee)为null,即使子选择中存在userid,我也没有值。 如果第一个选择中的null值返回null,是否可以使用适当的用户ID(子选择中的一个)并将0作为总和?
1, 100
2, 239
3, 0
4, 453
(in this case 3 is present in the subselect, but the sum is null
答案 0 :(得分:0)
使用isull函数。 选择用户ID,sum(isnull(fees,0)) 来自表1 在( 选择不同的用户ID 来自table2 条件1 = 2 和condition2 = 5 ) 按用户ID分组;
答案 1 :(得分:0)
您可以使用此:
select userid, COALESCE(sum(fees), 0)
from table1
where userid in (
select distinct userid
from table2
where condition1 = 2
and condition2 =5
)
group by userid;
根据函数“返回第一个参数,除非它为null,否则返回第二个参数”(在这种情况下为0)。
有关 Coalesce 的更多信息,请点击此处:
https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_coalesce
更新:
select t1.userid, COALESCE(sum(t1.fees), 0)
from table2 t2 left outer join table1 t1 on
T2.userid = t1.userid
where t2.condition1 = 2
and t2.condition2 =5
group by t1.userid;
答案 2 :(得分:0)
答案 3 :(得分:0)
我假设情况3中没有行,因为表1中没有用户行,因此您必须使用外部连接,例如
select users.userid , coalesce(sum(fees),0) from
(select distinct(userid) from table2
where condition1 = 2
and condition2 =5) users
left outer join table1 on table1.userid = users.userid
group by users.userid