我已經有以下查詢:保持SUM但限制選擇
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
一樣。但我仍然想獲得其他所有ingredients
的SUM()
。所以當ingredients_id
是1或巧克力,我仍然需要知道卡路里是總共500
而不是200
。所以基本上選擇cakes
,但現在基於蛋糕的成分。
現在我預計輸出爲1, Chocolate, , , 500, 25.50, ,
;但不是Example
蛋糕只是其中一種成分是巧克力的蛋糕。如果ingredients_id
是2,我希望兩個蛋糕都會被退回。
我希望預期的結果足夠清楚,如果不是,請讓我知道。
如果您已經編寫了您的查詢,然後顯示我們或至少您的預期輸出 – Ravi
編輯您的問題並顯示您想要的結果。如果您刪除了所有反引號,您的查詢也會更容易閱讀。 –