我正在设计一个人们发布短信的网站。用户可以对消息进行评级(1到5)。我将这个评分记录在表格中:
但我的投票数也很重要。例如,一张10票3票(30件)的帖子比2票5票(10票)更有价值。现在当我显示一个包含20条此消息的页面时,我想显示它们的评级
这是我的评级表:
create table ratings(
[id] int primary key identity(1,1),
[msgid] int,
[uid] int,
[rating] tinyint
)
我想从消息表中获取20条消息,其中包含每条消息的评级总和以及每条消息的评分计数。
select
msg.id, msg.text,
sum(rate.rating),
count(rate.id)
from
messages as msg
inner join
ratings as rate on msg.id = rate.msgid
group by
msg.id
任何人都可以帮我解决SQL查询代码吗?
答案 0 :(得分:2)
您无法选择group by
子句中未使用的列。
尝试:
select
msg.id, msg.text,
sum(rate.rating),
count(rate.id)
from
messages as msg
inner join
ratings as rate on msg.id = rate.msgid
group by
msg.id, msg.text
答案 1 :(得分:2)
您需要将group by
与select
进行协调。此外,考虑零评级,因此请使用左连接:
SELECT
msg.id,
msg.text,
SUM (COALESCE (rate.rating, 0) ) AS ratingSum,
COUNT (COALESCE (rate.id, 0) ) AS ratingCnt
FROM
messages as msg
LEFT JOIN
ratings rate ON msg.id = rate.msgid
GROUP BY
msg.id,
msg.text
答案 2 :(得分:0)
我认为这会奏效。
select msgid,
count(msgid) MsgCount,
sum(rating) RatingSum
from ratings
where msgid = [some msgid]
group by msgid, rating
这适用于大多数ANSI标准的transact sql平台。您可能必须为您的特定数据库修改它。
谢谢, --James Walsh Jr. - 大型开发商