保持SUM但限制选择

时间:2017-03-19 11:36:36

标签: mysql sql

我已经有了以下查询:

SELECT `c`.`id`, `cake`, `description`, `image`, SUM(`i`.`calories`) AS `calories`,  SUM(`i`.`sell_price`) AS `sell_price`, SEC_TO_TIME(SUM(TIME_TO_SEC(`i`.`time`))) as `time`, MIN(`i`.`stock`) AS `stock`
FROM `cakes` `c`
LEFT JOIN `recipes` `r`
    ON `c`.`id` = `r`.`cakes_id`
LEFT JOIN `ingredients` `i`
    ON `r`.`ingredients_id` = `i`.`id`
WHERE `r`.`ingredients_id` = ?
GROUP BY `c`.`id`

表格: 蛋糕:

| id | cake      | description |
|  1 | chocolate |             |
|  2 | Example   |             |

配方:

| id | cake_id | ingredient_id |
|  1 |       1 |             1 |
|  2 |       1 |             2 |
|  3 |       2 |             2 |

成分:

| id | ingredient | calories | buy_price | sell_price |
|  1 | Chocolate  |      200 |     12.22 |      14.00 |
|  2 | Sugar      |      300 |     10.50 |      11.50 |

但是当我运行此查询时,所有SUM()都针对该特定ingredients_id完成。

我想得到的结果是,所有内容仍然像没有WHERE一样被选中。但我仍然希望获得所有其他SUM()的{​​{1}}。因此,当ingredients为1或巧克力时,我仍然需要知道卡路里总共为ingredients_id而不是500。所以基本上选择200,但现在基于蛋糕的成分。

现在我希望输出为cakes;但不是1, Chocolate, , , 500, 25.50, ,蛋糕只是蛋糕,其中一种成分是巧克力。如果Example是2,我会期望两个蛋糕都归还。

我希望预期的结果足够明白,如果不是,请告诉我。

1 个答案:

答案 0 :(得分:2)

我很想你想要的是条件聚合。我只是不知道你想要它在哪些领域。也许:

SELECT c.id, c.cake, c.description, c.image,
       SUM(`i`.`calories`) AS `calories`, 
       SUM(CASE WHEN `r`.`ingredients_id` = ? THEN `i`.`sell_price` END) AS ingredient_sell_price, 
       SEC_TO_TIME(SUM(TIME_TO_SEC(`i`.`time`))) as `time`,
       MIN(CASE WHEN `r`.`ingredients_id` = ? THEN `i`.`stock` END) AS ingredient_stock
FROM cakes c LEFT JOIN 
     recipes r
     ON c.i` = r.cakes_id LEFT JOIN
     ingredients i
     ON r.ingredients_id = i.id
GROUP BY c.id;

编辑:

如果您只想要有巧克力的蛋糕,那么在进行聚合后您会找到的成分:

SELECT c.id, c.cake, c.description, c.image,
       SUM(i.calories) AS calories, 
       SUM(i.sell_price) AS ingredient_sell_price, 
       SEC_TO_TIME(SUM(TIME_TO_SEC(i.time))) as `time`,
       MIN(i.stock) AS ingredient_stock
FROM cakes c LEFT JOIN 
     recipes r
     ON c.i` = r.cakes_id LEFT JOIN
     ingredients i
     ON r.ingredients_id = i.id
GROUP BY c.id
HAVING SUM(r.ingredients_id = ?) > 0;

这将返回只有蛋糕具有您想要的特定成分。