0
我正在嘗試顯示已用特定標記標記的食譜列表。這是行得通的,除了我不能顯示標籤已被不同用戶應用於每本書的次數。我想按這個數字排序,例如,多個用戶標記爲「烘焙」的書會比只有一個用戶標記爲「烘焙」的書高。MySQL JOIN查詢問題/ COUNTs
下面是表的略微簡化的列表:
表1:食譜
ID, Title, Author, etc.
表2:配方
ID, recipe_title, recipe, cookbook_id
表3:recipe_reviews
ID, recipe_id, star_rating, comments
TABL E 4:book_tags
tag_id, tag_text
表5:book_user_tag
user_id, book_id, tag_id
這是目前編寫的測試查詢:
SELECT cookbooks.*, COUNT(DISTINCT recipe_reviews.ID) as numreviews, COUNT(book_user_tag.tag_id) as numtags, AVG(recipe_reviews.star_rating) as average, book_tags.tag_text
FROM cookbooks
LEFT OUTER JOIN recipes ON cookbooks.ID = recipes.cookbook_id
LEFT OUTER JOIN recipe_reviews ON recipes.ID = recipe_reviews.recipe_id
LEFT OUTER JOIN book_user_tag ON cookbooks.ID = book_user_tag.book_id
INNER JOIN book_tags ON book_user_tag.tag_id = book_tags.tag_id
WHERE book_user_tag.tag_id = 69
GROUP BY cookbooks.ID
ORDER BY numtags DESC
UPDATE:該查詢結束了工作,當我調試它,意識到在第二次計數中需要DISTINCT,並且它試圖計算錯誤的變量;應該是user_id。
很好的建議!我把它分解成基本知識,並意識到我在對錯誤變量進行COUNT處理。 – mandel 2010-11-04 21:01:55
非常好,我很樂意幫忙! – Infotekka 2010-11-04 21:11:49