2009-07-06 47 views
1

我有一張存儲用戶ID,對象ID和分數(+1或-1)的評分表。現在,當我想顯示一個對象列表,其總分數,+1票數和-1票數。最佳查詢收視率數據庫?

我怎樣纔能有效地做到這一點,而不必做SELECT COUNT(*)FROM評分WHERE(score = +/- 1 AND object_id = ..)?這是每個對象顯示的兩個查詢,這是不可接受的。數據庫設計是否合理?

+0

什麼數據庫? – 2009-07-06 05:02:49

+0

爲了判斷設計,我們需要一些設計要求。對於手頭的簡單任務來說,設計很好,因爲有一個簡單的解決方案。 – 2009-07-06 05:05:24

回答

1

雖然它並沒有解決您的合理設計問題,這裏,讓你一次這兩個方面的查詢:

select 
    sum(case when score = 1 then 1 else 0 end) 'positive' 
, sum(case when score = -1 then 1 else 0 end) 'negative' 
, objectId 
from 
    ratings 
where 
    objectId = @objectId ... 
group by 
    objectId 
0
select object_id, 
     sum(case when score = 1 then 1 else 0) upvotes, 
     sum(case when score = -1 then -1 else 0) downvotes, 
     sum(score) 
from ratings 
group by object_id 

也許類似的東西。

0

這應做到:

SELECT 
    UserID, ObjectID, 
    SUM(CASE WHEN score=1 Then 1 Else 0 End) as UpVotes, 
    SUM(CASE WHEN score=-1 Then 1 Else 0 End) as DownVotes, 
FROM YourTable 
GROUP BY UserID, ObjectID