当计数应该为零时,计数返回NULL

时间:2017-03-22 20:43:49

标签: mysql

我有一个跟踪用户可信度的表。

+-----------------+-----------------+-------------+
| user_id_1       | user_id_2       | is_trusted  |
+-----------------+-----------------+-------------+
| 1               | 2               | 0           |
...

其中1表示受信任,0表示不受信任。如果没有负反馈,我会得到值为NULL。有没有办法得到积极的 - 0?

select tr2.user_id_2 user,
    ((select count(*) plus
        from trust_ratings tr
        where is_trusted = 1 and
        tr2.user_id_2 = tr.user_id_2
        group by tr.user_id_2)
    -
    (select count(*) minus
        from trust_ratings tr
        where is_trusted = 0 and
        tr2.user_id_2 = tr.user_id_2
        group by tr.user_id_2)) as score
    from trust_ratings tr2
    group by user;

2 个答案:

答案 0 :(得分:1)

使用COALESCE()

select tr2.user_id_2 user,
    (
        coalesce(
        (select count(*) plus
        from trust_ratings tr
        where is_trusted = 1 and
        tr2.user_id_2 = tr.user_id_2
        group by tr.user_id_2), 0)
    -
        coalesce(
        (select count(*) minus
        from trust_ratings tr
        where is_trusted = 0 and
        tr2.user_id_2 = tr.user_id_2
        group by tr.user_id_2), 0)
    ) as score
    from trust_ratings tr2
    group by user;

答案 1 :(得分:1)

您可以使用case when

select   user_id_2 user,
         sum(case is_trusted when 1 then 1 else -1 end) as score
   from  trust_ratings
group by user;

或者:

select   user_id_2 user,
         sum(is_trusted * 2 - 1) as score
   from  trust_ratings
group by user;