使用MySQL在JOIN中使用JOIN获取SUM

rya*_*anb 13 mysql sql database join group-by

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 |
+------------+--------+
Run Code Online (Sandbox Code Playgroud)

我的目标是获得每个部门中具有5星评级的所有产品的总价.像这样的东西.

+------------+-------------+
| department | total_price |
+------------+-------------+
| Clothes    | 36.00       |  /* T-Shirt and Skirt */
| Toys       | 90.00       |  /* Fire Truck and Bike */
+------------+-------------+
Run Code Online (Sandbox Code Playgroud)

如果可以的话,我想在没有子查询的情况下这样做.起初我尝试使用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 |
+------------+------------+
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,玩具部门的价格是不正确的,因为自行车有两个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 |
+------------+---------------------+
Run Code Online (Sandbox Code Playgroud)

但随后服装部门关闭,因为两种产品的价格相同.

目前我的解决方案涉及采取产品(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 |
+------------+-------------+
Run Code Online (Sandbox Code Playgroud)

但这感觉就像这样一个愚蠢的黑客.没有子查询,有更好的方法吗?谢谢!

OMG*_*ies 18

使用:

  SELECT p.department,
         SUM(p.price) AS total_price
    FROM PRODUCTS p
    JOIN (SELECT DISTINCT 
                 r.product_id,
                 r.rating
            FROM RATINGS r) x ON x.product_id = p.id
                             AND x.rating = 5
GROUP BY p.department
Run Code Online (Sandbox Code Playgroud)

从技术上讲,这不使用子查询 - 它使用派生表/内联视图.

将此标记为社区维基因为某些猴子一直在低估我,尽管它是100%正确的.

  • 打了一下猴子 (6认同)