Mysql 选择最特定的联接结果
我试图让mysql返回一个shopitem最具体的折扣,因为可能会有几个折扣。我的表格和数据如下(不相关的列被省略): 我预期的查询输出是Mysql 选择最特定的联接结果,mysql,sql,join,Mysql,Sql,Join,我试图让mysql返回一个shopitem最具体的折扣,因为可能会有几个折扣。我的表格和数据如下(不相关的列被省略): 我预期的查询输出是 itemId price discountPrice =================================== Item1 100 80 Item2 100 60 Item3 100 40 Item4 100 (null) 正如你所看到的,我的规则是 供应商折扣是最不明确的 供应商+品牌折扣更具体
itemId price discountPrice
===================================
Item1 100 80
Item2 100 60
Item3 100 40
Item4 100 (null)
正如你所看到的,我的规则是
选择item.itemId、item.price、discount.discountPrice从项目左侧加入折扣(item.itemId=discount.itemId)或(item.brand=discount.brand和item.supplier=discount.supplier)或(item.supplier=discount.supplier和discount.brand为NULL)
我会这样做:
对所有三个折扣使用单独的左连接,并从中选择最具体的折扣
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服务器来实际运行它。下面是我的方法: 对所有三个折扣使用单独的左连接,并从中选择最具体的折扣
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服务器来实际运行它。查询:
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) |
查询:
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) |