2012-07-05 97 views
1

我想顯示一張照片庫和每張照片評分的次數。選擇的SQL計數

這裏是我的簡單的查詢,但不知道如何從收視率表的計數。

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 

每次點擊的星級按鈕,一個新的記錄被插入到表評級。我只允許將照片評分爲100次,因此我想要顯示用戶瀏覽圖庫時照片的評分次數(即57/100)。

感謝您的幫助!

回答

0

您可以使用帶有group by語句的count函數來計算評級。

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 
+0

謝謝兩位! COALESCE - 對我來說這是一個新的! – user1505054 2012-07-05 20:47:48

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