帮助SQL连接

时间:2011-07-18 19:18:43

标签: mysql

我有3张表a)BOOKS (id,name) b)RATINGS (book id,rating,ip address) c)comments (comment_id,book id,comments,date)

我想使用左连接显示BOOK NAME,RATING,COMMENTS数量。

我的查询的问题是,如果评论数量发生变化,它会显示不同的评分 例如,如果有一本书的评论,则sql返回的数据是完美的,但是当添加更多评论时,评级显示不正确。

SELECT
    book.id,
    book.name,SUM( rtng.rating ) As total_rating,
    COUNT(distinct cmt.comment_id ) AS comment_count
FROM books book
    LEFT JOIN ratings rtng ON rtng.book_id = book.id
    LEFT JOIN comments cmt ON cmt.book_id = book.id

4 个答案:

答案 0 :(得分:0)

这可能与books表和comments(和ratings)表之间的关系是“一对多”的事实有关。您将不得不至少进行两次查询:

(伪代码如下)

all_book_ids = SELECT book_id FROM books

foreach a_single_book in all_book_ids
    SELECT * FROM comments WHERE book_id = a_single_book
    SELECT * FROM ratings  WHERE book_id = a_single_book

答案 1 :(得分:0)

如何基于书籍ID分组并另外计算平均评分?

SELECT book.id,
       book.name,
       SUM( rtng.rating )              AS total_rating
       AVG( rtng.rating )              AS averageRating,
       COUNT(distinct cmt.comment_id ) AS comment_count
  FROM books                           AS book
  LEFT JOIN ratings rtng 
         ON rtng.book_id = book.id
  LEFT JOIN comments cmt 
         ON cmt.book_id = book.id    
  GROUP BY book.id

答案 2 :(得分:0)

再来一次

SELECT book.id,book.name,
rtng.total_rating,
cmt.comment_count
from books book 
LEFT JOIN 
(
select book.id,book.name, SUM( rtng.rating ) As total_rating
from books book
inner join ratings rtng 
ON rtng.book_id = book.id 
group by book.id,book.name
)rtng 
ON rtng.book_id = book.id 

LEFT JOIN 
(
select book.id,book.name, COUNT(*) AS comment_count 
from books book
    left join comments cmt 
    ON cmt.book_id = book.id
group by book.id,book.name
)cmt 
ON cmt.book_id = book.id

答案 3 :(得分:0)

通过这种方式,您可以获得所有书籍,无论是否缺少评分或评论......主要表格是书籍,然后分别加入每个评论和评级。

select
      B.ID,
      B.Name,
      COALESCE( TR.Rating, 0 ) TotalRating,
      COALESCE( TR.AvgRating, 0 ) AvgRating,
      COALESCE( COM.CommentCnt, 0 ) TotalComents
   FROM
      Books B
         LEFT JOIN ( select R.Book_ID,
                            SUM( R.Rating ) Rating,
                            AVG( R.Rating ) AvgRating
                        FROM Ratings R
                        Group By R.Book_ID ) TR
            ON B.ID = TR.Book_ID

         LEFT JOIN ( select C.Book_ID, 
                            count(*) CommentCnt
                        FROM Comments C
                        Group by C.Book_ID ) COM
            ON B.ID = COM.Book_ID