我在MySQL 5.1.38中有两个表。使用MySQL在GROUP BY中使用JOIN获得SUM
products
+----+------------+-------+------------+
| id | name | price | department |
+----+------------+-------+------------+
| 1 | Fire Truck | 15.00 | Toys |
| 2 | Bike | 75.00 | Toys |
| 3 | T-Shirt | 18.00 | Clothes |
| 4 | Skirt | 18.00 | Clothes |
| 5 | Pants | 22.00 | Clothes |
+----+------------+-------+------------+
ratings
+------------+--------+
| product_id | rating |
+------------+--------+
| 1 | 5 |
| 2 | 5 |
| 2 | 3 |
| 2 | 5 |
| 3 | 5 |
| 4 | 5 |
| 5 | 4 |
+------------+--------+
我的目标是获得所有产品的总价格,每个部门都有5星评级。像这样的东西。
+------------+-------------+
| department | total_price |
+------------+-------------+
| Clothes | 36.00 | /* T-Shirt and Skirt */
| Toys | 90.00 | /* Fire Truck and Bike */
+------------+-------------+
我想这样做没有子查询,如果我可以。起初,我试着用sum()来加入。
select department, sum(price) from products
join ratings on product_id=products.id
where rating=5 group by department;
+------------+------------+
| department | sum(price) |
+------------+------------+
| Clothes | 36.00 |
| Toys | 165.00 |
+------------+------------+
正如你所看到的价格为玩具部门因为有自行车两个5星评级,因此计数是价格的两倍,由于加入不正确。
我然后尝试添加不同的总和。
select department, sum(distinct price) from products
join ratings on product_id=products.id where rating=5
group by department;
+------------+---------------------+
| department | sum(distinct price) |
+------------+---------------------+
| Clothes | 18.00 |
| Toys | 90.00 |
+------------+---------------------+
但后来衣服部门关闭,因为两个产品共享相同的价格。
目前,我的解决方法包括采取独特的产品(id),并使用它来使价格独一无二。
select department, sum(distinct price + id * 100000) - sum(id * 100000) as total_price
from products join ratings on product_id=products.id
where rating=5 group by department;
+------------+-------------+
| department | total_price |
+------------+-------------+
| Clothes | 36.00 |
| Toys | 90.00 |
+------------+-------------+
但是,这感觉就像这样一个愚蠢的黑客。没有子查询有没有更好的方法来做到这一点?谢谢!
你有什么反对的子查询? – 2010-07-23 17:42:54
我的连接和条件更加复杂和动态,而且我的ORM(活动记录)不能很好地支持子查询。 – ryanb 2010-07-23 17:45:09
你怎么知道从第二个表到哪个部门评分? – 2010-07-23 17:46:05