选择中的SQL计数

时间:2012-07-05 20:08:46

标签: sql count

我想展示一张照片库以及每张照片的评分次数。

这是我的简单查询,但不确定如何从评级表中获取计数。

SELECT
   Photo.photoID
  ,Photo.photoName
  ,Member.memberID
  ,Member.memberFName
  ,Rating.ratingID
FROM
  Photo
INNER JOIN Member ON Photo.memberID = Member.memberID
LEFT OUTER JOIN Rating ON Photo.photoID = Rating.photoID
ORDER BY Photo.photoID DESC

每次有人点击Star Rating按钮时,都会在Rating表中插入一条新记录。我只允许对照片进行100次评级,因此我希望在用户浏览图库时显示照片被评级的次数(即57/100)。

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

select p.photoID,
    p.photoName,
    m.memberID,
    m.memberFName,
    coalesce(rc.Count, 0) as RatingCount
from Photo p
inner join Member m on p.memberID = m.memberID
left outer join (
    select photoID, count(*) as Count
    from Rating
    group by photoID
) rc on p.photoID = rc.photoID
order by p.photoID desc

答案 1 :(得分:0)

您可以将count函数与group by语句一起使用以获取评级计数。

select p.photoID,
p.photoName,
m.memberID,
m.memberFName,
count(r.RatingID) as RatingCount
from Photo p
inner join Member m on p.memberID = m.memberID
left outer join Rating r on p.photoID = r.photoID
group by p.photoID, p.photoName, m.memberID, m.memberFName