我正在尝试让 mysql 返回商店商品的最具体折扣,因为可能会有几个折扣。我的表格和数据如下(不相关的列被省略了):
Item
itemId brand supplier price
====== ===== ======== =====
Item1 Brand1 Supply1 100
Item2 Brand2 Supply1 100
Item3 Brand3 Supply1 100
Item4 Brand4 Supply2 100
Discount
discountId itemId brand supplier discountPrice
========== ====== ====== ======== =============
Discount1 (null) (null) Supply1 80
Discount2 (null) Brand2 Supply1 60
Discount3 Item3 (null) (null) 40
我预期的查询输出将是
itemId price discountPrice
===================================
Item1 100 80
Item2 100 60
Item3 100 40
Item4 100 (null)
如您所见,我的规则是
- 供应商折扣是最不具体的
- 供应商+品牌折扣更具体
- ItemId 折扣是最具体的
但是,带有 or 子句的普通左连接将返回所有组合,而不是最具体的折扣。我怎样才能做到这一点?
select item.itemId, item.price, discount.discountPrice from item left join discount on (item.itemId = discount.itemId) or (item.brand = discount.brand and item.supplier = discount.supplier) or (item.supplier = discount.supplier AND discount.brand IS NULL)