MySQL - SUM / COUNT来自不同表的不同列

时间:2013-06-22 04:15:13

标签: mysql left-join aggregate-functions

我有一个特殊的问题。给出了三个表格。

product  
 - id
 - title

product_rating 
 - product_id
 - rating

product_view
 - product_id

我想抓住产品的评级为SUM(可能是+1或-1值)及其总产品数。

SELECT 
    p.`id`, p.`title`,
    SUM( pr.`rating` ) AS rating, 
    COUNT( pv.`product_id` ) AS views 
FROM 
    `product` AS p 
    LEFT JOIN `product_rating` AS pr ON ( pr.`product_id` = p.`id` ) 
    LEFT JOIN `product_view` AS pv ON ( pv.`product_id` = p.`id` ) 
GROUP BY 
    p.`id`
ORDER BY rating DESC

在表格中我有1个评分,9个观点。但是,查询返回9个评级,9个视图。我理解为什么正在发生(它是对每个product_view的评级总结),但我不知道如何绕过它。

任何建议都将不胜感激。


示例数据:

product
------------
id | title  
1  | Globber  

product_rating
-------------------
product_id | rating  
1          | 1  

product_view
------------
product_id  
1  
1  
1  
1  
1  
1  
1  
1  
1  

2 个答案:

答案 0 :(得分:3)

尝试

SELECT p.id, p.title, r.rating, v.views
  FROM product p LEFT JOIN
( 
  SELECT product_id, SUM(rating) rating
    FROM product_rating
   GROUP BY product_id
) r ON p.id = r.product_id LEFT JOIN
(
  SELECT product_id, COUNT(*) views
    FROM product_view
   GROUP BY product_id
) v ON p.id = v.product_id
ORDER BY r.rating DESC

示例输出:

| ID |   TITLE | RATING | VIEWS |
---------------------------------
|  1 | Globber |      1 |     9 |

这是 SQLFiddle 演示

答案 1 :(得分:0)

怎么做?

SELECT tbl.pid,tbl.ptitle, SUM(tbl.rating) as Rate, COUNT (tbl.views) as ViewList FROM (SELECT 
p.`id` as pid, p.`title` as ptitle,
pr.`rating` AS rating, 
pv.`product_id` AS views 
 FROM 
`product` AS p 
LEFT JOIN `product_rating` AS pr ON ( pr.`product_id` = p.`id` ) 
LEFT JOIN `product_view` AS pv ON ( pv.`product_id` = p.`id` ) ) as tbl
GROUP BY 
tbl.`pid`
ORDER BY tbl.Rate DESC