2017-03-22 15 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

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

かを? –

+0

はい、正しい番号が付けられています。 –

答えて

1

あなたはcase when使用することができますあなたが個別に各クエリを試してみました

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; 
関連する問題