MYSQL查询,平均多个表

时间:2017-02-12 21:24:13

标签: mysql

需要帮助将MYSQL查询放在一起,返回以下内容(如果可能的话)。目前,我用两个查询提取了我需要的数据,但如果只用一个查询就可以完成,那就很高兴。

我有两张桌子。一个文档表,列出所有可用文档。我还有一张表格,里面有不同文件的评级。每个文档都有多个评级,我对文档的平均评分感兴趣。

表格文件

+-------+------------+
| docId | docTitle   |
+----+---------------+
|  1    | Doc1 title |
|  2    | Doc2 title |
+-------+------------+

表评论

+------------+---------------+
| docId      | commentRating |
+------------+---------------+
| 1          |    5          |
| 1          |    3          |
| 2          |    1          |
| 2          |    4          |
+------------+---------------+

从查询中返回结果

+----+------------+-----------+
| id | title      | avgRating |
+----+------------+-----------+
|  1 | Doc1 title |    4      |
|  2 | Doc2 title |    2,5    |
+----+------------+-----------+

解决! 我使用此查询来获得我想要的结果:

SELECT doc.docId, doc.docTitle, doc.docThumbnail, averageRating
    from `document` as doc 
    Left join (
        select * , avg(commentRating) 
        as averageRating from comments 
        group by comments.docId
    )
    as rat On commentRating = doc.docid

1 个答案:

答案 0 :(得分:0)

如果您只需要平均值,请通过分组查询中的聚合函数AVG()选择它:

 Select doc.docid as id , doc.docTitle , rat.average
 from document as doc
 Left join (
    select * , avg( commentRating ) as average
       -- , group_concat(rating) as allratings
    from comments
    group by commentDocId
    ) as rat
 On rat.commentDocId = doc.docid

注意:allratings会返回所选docId的所有评级。如果没用,请将其删除。