选择记录顺序为另一个表的计数,而不是在Mysql中检索正确的计数

时间:2015-03-15 08:03:16

标签: mysql sql join left-join

在mysql db中,我有两个表bookratingtable

书籍表有三个字段ID,uniqueid,Title

评级表有三个字段Book_ID,userid,rating

我需要一个检索记录group by id(书表)和order by count(rating)(评级表)的查询。

我尝试了这样的查询:

SELECT book.ID,book.Title,COUNT(ratingtable.rating) AS views
FROM book LEFT JOIN ratingtable ON book.ID = ratingtable.book_ID
GROUP BY book.ID
ORDER BY views DESC

但是对于三个值,它显示错误的计数值。我不知道会发生什么。

修改 ratingtable:

enter image description here

书:

enter image description here

这里答案[count(rating)]应为1。但它显示

enter image description here 帮我解决这个问题。

2 个答案:

答案 0 :(得分:1)

您获得的结果实际上非常正确,因为您的图书ID不是唯一的。但是,要获得您想要的计数,您可以使用子查询首先对书籍进行分组,然后进行计数:

SELECT b2.ID, b2.Title,COUNT(ratingtable.rating) AS views
FROM 
    (SELECT b1.id, b1.title FROM Book b1 Group by b1.id, b1.title) b2 
LEFT JOIN ratingtable ON b2.ID = ratingtable.book_ID
GROUP BY b2.ID, b2.Title
ORDER BY views DESC

答案 1 :(得分:1)

您需要按书名和标题进行分组。

SELECT book.ID, book.Title, COUNT(ratingtable.rating) AS views
FROM book LEFT JOIN ratingtable ON book.ID = ratingtable.book_ID
GROUP BY book.ID, book.Title
ORDER BY views DESC

或使用相关的子查询来计算:

select distinct book.ID,
                book.Title,
                (select count(*) from ratingtable
                 where book.ID = ratingtable.book_ID) as views
from book
ORDER BY views DESC