我要执行一个相当复杂的逻辑查询。本质上有一系列相关的表。我很难找到处理它的好方法。
表格:
交易 -
T_id
折扣 -
D_id
item_id
类型(百分比或基值)
值
交易折扣 -
T_id
D_id
项目 -
item_id
价格
编辑:附加表格
购买
T_id
item_id
我正在尝试提取应用折扣后调整后的价格。我想避免在数据库中添加另一列调整后的价格...因为可以根据已输入的数据计算每笔交易的调整后价格(因此存储此数据是多余的)。
这是基本逻辑:
if(this transaction had a discount applied)
//apply the discount and return the adjusted price
else(no discount applied)
//pull price
可以使用 PHP 逻辑在多个单独的查询中执行此操作。
//1st step - create an array of bool's: true = discount_used/false = no_discount
//2nd step - if(discount_used) return price adjusted to discount
//3rd step - if(no_discount) return price
//4th step - combine the two different arrays
这显然非常笨重。似乎必须有一种更好的方法来执行此操作,而且效率可能更高。
据我了解,您可以在 mysql 中执行包含逻辑的查询,这对这里有帮助吗?
最佳答案
假设您在交易表中有一个 item_id,并且该百分比由“P”表示,您可以尝试类似的方法
SELECT *,
CASE
WHEN td.T_id IS NULL
THEN it.price
WHEN td.T_id IS NOT NULL AND d.Type = 'P'
THEN id.price - (id.price * d.value)
ELSE id.price - d.value
END PriceDiscounted
FROM Transaction t LEFT JOIN
Purchase p ON t.T_id = p.T_id LEFT JOIN
Item it ON p.item_id = it.item_id LEFT JOIN
Transaction_Discount td ON t.T_id = td.T_id LEFT JOIN
Discount d ON td.D_id = d.D_id LEFT JOIN
Item id ON d.item_id = id.item_id
关于sql - 如何处理这个特定的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2095496/