【发布时间】:2011-03-20 06:00:09
【问题描述】:
我在 MySQL 5.1.38 中有两个表。
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 |
+------------+------------+
如您所见,玩具部门的价格不正确,因为 Bike 有两个 5 星评级,因此由于加入,该价格被计算了两次。
然后我尝试在总和中添加 distinct。
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 |
+------------+-------------+
但这感觉就像一个愚蠢的黑客。没有子查询有没有更好的方法来做到这一点?谢谢!
【问题讨论】:
-
你对子查询有什么看法?
-
我的联接和条件更加复杂和动态,我的 ORM(Active Record)不能很好地支持子查询。
-
你如何从你的第二张表中知道评级属于哪个部门?
-
@Charles,你是说收视率表吗?它根据所属的产品(product_id)知道部门。
-
使用 Active Record 有什么限制?你可以使用两个查询吗?可以使用内联表定义吗?
标签: sql mysql database join group-by