开发者

MySQL - Use GROUP_CONCAT values in a calculation?

开发者 https://www.devze.com 2023-03-08 16:33 出处:网络
I am trying to create a query which will give me a product\'s value 开发者_运维技巧after a number of discounts have been taken off its initial value.

I am trying to create a query which will give me a product's value 开发者_运维技巧after a number of discounts have been taken off its initial value.

This is a simplified version of what I have so far:

SELECT
p.price
GROUP_CONCAT(d.amount) AS discounts
FROM products p
LEFT OUTER JOIN discounts d
ON d.product_id = p.id
GROUP BY p.id

Where discounts.amount is a decimal value.

Edit: For example, if there were two corresponding discounts with values 10 and 15 respectively and the initial product price was 50, the calculation would return 25

Is there anyway within the query that I can perform the calculation that I want?

Any advice would be greatly appreciated.

Thanks.


There is a SUM() method:

SELECT p.price,
       p.price - COALESCE(SUM(d.amount), 0) as discounted_price,
       GROUP_CONCAT(d.amount) AS discounts
FROM products p
LEFT OUTER JOIN discounts d
ON d.product_id = p.id
GROUP BY p.id
0

精彩评论

暂无评论...
验证码 换一张
取 消