1

我正在尝试让 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)

如您所见,我的规则是

  1. 供应商折扣是最不具体的
  2. 供应商+品牌折扣更具体
  3. 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)

4

2 回答 2

1

询问:

SQLFIDDLE示例

SELECT i.itemId, 
       i.price, 
       COALESCE(d.discountPrice, d2.discountPrice, d3.discountPrice) AS discountPrice 
FROM item i
LEFT JOIN discount d 
  ON i.itemId = d.itemId
LEFT JOIN discount d2
  ON i.brand = d2.brand
  AND i.supplier = d2.supplier 
LEFT JOIN discount d3
 ON i.supplier = d3.supplier 
 AND d3.brand IS NULL

结果:

| ITEMID | PRICE | DISCOUNTPRICE |
----------------------------------
|  Item1 |   100 |            80 |
|  Item2 |   100 |            60 |
|  Item3 |   100 |            40 |
|  Item4 |   100 |        (null) |
于 2013-07-11T08:41:27.530 回答
0

这是我的做法:对所有三个折扣使用单独的左连接并从中选择最具体的

Select 
    i.itemId, 
    i.price,
    coalesce(spec3.discountPrice, spec2.discountPrice, spec1.discountPrice)
from item i
left join Discount spec3 on (i.itemId = spec3.itemId)
left join Discount spec2 on (i.supplier = spec2.supplier and i.brand = spec2.brand)
left join Discount spec1 on (i.supplier = spec1.supplier)

上面的查询可能包含一些语法错误,我附近没有 mysql 服务器来实际运行它。

于 2013-07-11T08:37:53.640 回答