mysql - 选择最具体的连接结果

标签 mysql sql join

我正在尝试让 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 进行正常的左连接将返回所有组合,而不是最具体的折扣。我怎样才能做到这一点?

选择 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 ) 或 (item.supplier = discount.supplier AND discount.brand IS NULL)

最佳答案

查询:

SQLFIDDLEEXample

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) |

关于mysql - 选择最具体的连接结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17588538/

相关文章:

php - 如何计算具有匹配 ID 的行数?

php - 显示动态创建路径中的图像

sql - 处理动态(用户提供的)列名

sql-server - 带有 WHERE 子句的 LEFT OUTER JOIN

涉及超过 2 个表的 mySQL SELECT Left Outer Join

PHP - 使用新列将 XML 插入 MySQL 数据库

php - 当结果为空时,“SELECT FOUND_ROWS()”返回至少 1

sql - 随机选择并不总是返回单行

sql - ORA-12154 : TNS:could not resolve the connect identifier specified on a table

join - 分片如何处理关联表的连接?