Use COALESCE in SUM in MySQL SELECT statement
I have the following tables:
Table users
id name base_discount
1 jack 10
2 michael 20
3 richard 30
Table item
id name category_id price
1 hammer 1 10
2 knife 2 15
3 spoon 2 12
4 plate 3 20
5 tree 4 400
Table category
id name
1 tools
2 kitchen
3 dishes
4 garden
Table discount_category
id user_id category_id discount
1 1 1 20
2 1 3 25
3 3 3 10
4 1 2 15
Table discount_item
id user_id item_id discount
1 2 1 50
2 1 2 50
Now what do I want to achieve. I want to attach a discount for an item the user has for the correct item. If this is not available (NULL), I want to bind the discount to the category the user has. And if this is not available (NULL), I want to attach the base discount that the user has. With the discount, I then calculate the new price of the item. However, when I try to use COALESCE () in SUM (), I get a syntax error. What am I doing wrong?
Below is my current request:
SELECT item.id, item.name, category.id,
category.name AS category_name, item.price, SUM((100 -
COALESCE(
(
SELECT discount_item.discount
FROM discount_item
INNER JOIN users ON discount_item.user_id = users.id
WHERE users.id = '1' AND discount_item.item_id = item.id
),
(
SELECT discount_category.discount
FROM discount_category
INNER JOIN users ON discount_category.user_id = users.id
WHERE users.id = '1' AND discount_category.category_id = item.category_id
),
(
SELECT users.base_discount
FROM users
WHERE users.id = '1'
)
)) / 100 * item.price) AS new_price,
FROM item
INNER JOIN category ON item.category_id = category.id;
Also see below link for SQL Fiddle (failed to do this on sqlfiddle.com as it won't load). In the example, I added a suffix for each table name. http://rextester.com/LCCKSD59098
source to share
You have an extra comma after new_price
and before FROM ITEM
, hence the error.
-
Do not select other columns in the list, if you do not use them in a group like in other relational DBMSs, you will get an error.
-
Also use
alias
for table names for better readability and to avoid confusion.
source to share