简体   繁体   English

MySQL JOIN查询/ COUNT个问题

[英]Problem with MySQL JOIN query / COUNTs

I am trying to display a list of cookbooks which have been tagged with a specific tag. 我正在尝试显示已用特定标签标记的食谱列表。 This is working, except I cannot also display the number of times the tag has been applied to each book by different users. 这是可行的,除了我也无法显示不同用户将标签应用于每本书的次数。 I would like to sort by this number so a book tagged 'baking' for example, by multiple users, would rank higher than a book tagged 'baking' by only one user. 我想按此数字进行排序,因此,例如,由多个用户标记为“烘焙”的书的排名将比仅由一个用户标记为“烘焙”的书的排名更高。

Here is a slightly simplified list of tables: 这是一个稍微简化的表列表:

Table 1: cookbooks 表1:菜谱

ID, Title, Author, etc.

Table 2: recipes 表2:食谱

ID, recipe_title, recipe, cookbook_id

Table 3: recipe_reviews 表3:recipe_reviews

ID, recipe_id, star_rating, comments

Table 4: book_tags 表4:book_tags

tag_id, tag_text

Table 5: book_user_tag 表5:book_user_tag

user_id, book_id, tag_id

This is the test query as currently written: 这是当前编写的测试查询:

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: This query ended up working when I debugged it and realized that a DISTINCT was required on the second count, and that it was trying to count the wrong variable; 更新:此查询在调试时结束,并且意识到第二个计数需要DISTINCT,并且它试图计算错误的变量; should have been user_id. 应该是user_id。

若要调试此问题,请尝试使用简单的SELECT *并删除GROUP BY子句和COUNT字段,这样可以看到在分组之前生成的原始数据,您可能会发现联接未按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM