我有一个评级表,用于存储用户ID,对象ID和分数(+1或-1)。现在,当我想显示一个对象列表,其总分,+1票数和-1票数。
如何有效地执行此操作而无需执行SELECT COUNT(*)FROM rating WHERE(score = +/- 1 AND object_id = ..)?这是每个对象显示的两个查询,这是不可接受的。数据库设计合理吗?
答案 0 :(得分: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
答案 1 :(得分: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
也许就是这样。
答案 2 :(得分: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