2017-03-22 26 views
0

我有一個表跟蹤用戶的可信度。計數返回NULL時,它應該只是零

+-----------------+-----------------+-------------+ 
| 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; 
+0

你逐一嘗試查詢? –

+0

是的,他們給出了正確的數字。 –

回答

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; 
+0

這只是加起來的信託,但我想從信託減去不信任給整體信任 –

+0

啊是的,我錯過了。使用'sum'和'else -1'更新了我的答案。我不會使用2個子查詢,這使得引擎訪問表3次。 – trincot

+0

添加了更短的版本。 – trincot

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; 
相關問題