MySQL聚合?

时间:2012-09-01 20:23:37

标签: mysql

我有以下两个表

Table: items
ID  |  TITLE
249 | One
250 | Two
251 | Three

我已经为这些投票了:

Table: votes
VID | IID | userid | votes
01  | 249 |    6   | 5
02  | 249 |    7   | -5
03  | 249 |    8   | 5
04  | 249 |    9   | 5
05  | 250 |    6   | -5
06  | 250 |    7   | -5
07  | 250 |    8   | 5

-5表示DOWNVOTE,+ 5表示upvote。假设我以用户6身份登录,SQL查询会给我什么:

Table: result
ID  |  TITLE | TOTALVOTES | UPVOTES | DOWNVOTES | CURRENTUSERVOTED
249 | One    | 4          | 3       | 1         | 1
250 | Two    | 3          | 1       | 2         | 1
251 | Three  | 0          | 0       | 0         | 0

2 个答案:

答案 0 :(得分:2)

在汇总函数中使用CASE个表达式:

SELECT    a.ID,
          a.TITLE,
          COUNT(b.IID) AS TOTALVOTES,
          COUNT(CASE WHEN b.votes =  5 THEN 1 END) AS UPVOTES,
          COUNT(CASE WHEN b.votes = -5 THEN 1 END) AS DOWNVOTES,
          COUNT(CASE WHEN b.userid = 6 THEN 1 END) AS CURRENTUSERVOTED
FROM      items a
LEFT JOIN votes b ON a.ID = b.IID
GROUP BY  a.ID,
          a.TITLE

答案 1 :(得分:0)

这应该有效

select I.Id, I.Title, count(*) as TotalVotes,
sum(case when votes > 0 then 1 else 0 end) as UPVOTES, 
sum(case when votes < 0 then 1 else 0 end) as DOWNVOTES,
case when sum(Case when userid = @userloged then 1 else 0 end) = 1 then 1 else 0 end as CURRENTUSERVOTED
from items I
LEFT JOIN Votes V
on I.Id = V.IID
group by I.ID, I.Title

可能是获得CURRENTUSERVOTED的更好方法