我有一个商品表和一个评论表。
我想编写一个查询以返回每种产品的评论的COUNT和AVG。
AND ,如果没有评论,我希望它为COUNT和AVG返回0 / null。
产品表
+--------+----------+
| prodId | prodName |
+--------+----------+
| 1 | apple |
| 2 | banana |
| 3 | cacao |
+--------+----------+
查看表
+----------+----------+--------+
| reviewId | prodId | rating |
+----------+----------+--------+
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 2 | 5 |
| 4 | 2 | 5 |
+----------+----------+--------+
这就是我想要的结果:
+--------+----------+--------+-------+
| prodId | prodName | avg | count |
+--------+----------+--------+-------+
| 1 | apple | 1 | 2 |
| 2 | banana | 5 | 2 |
| 3 | cacao | null | 0 |
+--------+----------+--------+-------+
我能够获得带有评论的产品的COUNT和AVG
SELECT p.prodid, p.prodname, avg(r.stars), count(r.productid)
FROM products p
INNER JOIN reviews r ON p.productid=r.productid
GROUP BY p.productid
+--------+----------+--------+-------+
| prodId | prodName | avg | count |
+--------+----------+--------+-------+
| 1 | apple | 1 | 2 |
| 2 | banana | 5 | 2 |
+--------+----------+--------+-------+
对于没有评论的产品,我也可以获得COUNT和AVG
SELECT p.prodid, p.prodname, avg(r.stars), count(r.stars)
FROM products p
LEFT OUTER JOIN reviews r
ON (p.productid=r.productid) WHERE r.productid IS NULL
GROUP BY p.productid
+--------+----------+--------+-------+
| prodId | prodName | avg | count |
+--------+----------+--------+-------+
| 3 | cacao | null | 0 |
+--------+----------+--------+-------+
但是我不知道MySql是否可以查询和计数匹配的结果并计算一次查询中不匹配的结果。
答案 0 :(得分:0)
只需从第二个查询中删除where condition
SELECT p.prodid, p.prodname, avg(r.stars), count(r.stars)
FROM products p
LEFT OUTER JOIN reviews r
ON p.productid=r.productid
GROUP BY p.productid,p.prodname
答案 1 :(得分:0)
在MySQL中,“ LEFT JOIN”实际上与LEFT OUTER JOIN相同。 OUTER关键字是可选的。 要获得结果,您只需要执行简单的“ LEFT JOIN”并按ID(或任何其他唯一键)进行分组:
SELECT
`p`.`prodId` AS `ID`,
`p`.`prodName` AS `Product`,
avg(`r`.`rating`) AS `AVG Rating`,
count(`r`.`reviewId`) AS `Vote Count`
FROM `products` AS `p`
LEFT JOIN `reviews` AS `r` ON `p`.`prodId` = `r`.`prodId`
GROUP BY `p`.`prodId`