我有以下表格:内使用SUM COALESCE在MySQL中的SELECT语句
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
现在我想实现。我想附加用户对正确项目的每件商品的折扣。如果不可用(NULL)我想附加用户拥有的每个类别的折扣。如果这不可用(NULL),我想附加用户拥有的基本折扣。然后用折扣计算该物品的新价格。但是,当我尝试使用SUMES()内的COALESCE()时,我得到一个语法错误。我究竟做错了什么?
下面是我当前的查询:
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;
另请参阅下面的链接的SQL小提琴(不能这样做在sqlfiddle.com,因为它不会加载)。在这个例子中,我为每个表名添加了一个后缀。 http://rextester.com/LCCKSD59098
不错,但请看:[为什么我应该提供一个用于我认为是非常简单的SQL查询的MCVE?](https://meta.stackoverflow.com/questions/333952/why-应该-I-提供-AN-MCVE换什么,似乎对我将要-A-极简单的SQL查询) – Strawberry
你要一个'sum'没有'组by'。这是故意的吗? – Utsav
@Strawberry请参阅http://rextester.com/JAQS56832。我会将其添加到我的问题。 – njs