我正在阅读这本书,在第15章中更新数据集,在需要您解决的问题部分中,有以下问题:
将配件零售价格(类别= 1)设置为价格最高的供应商的批发价加上35 %
我有点不明白为什么作者要给出这个解决方案:
UPDATE Products
SET
RetailPrice = ROUND(1.35 * (
SELECT DISTINCT WholesalePrice
FROM Product_Vendors
WHERE Product_Vendors.ProductNumber =
Products.ProductNumber
AND WholesalePrice = (
SELECT MAX(WholesalePrice)
FROM Product_Vendors
WHERE Product_Vendors.ProductNumber =
Products.ProductNumber)),0)
WHERE RetailPrice < 1.35 * (
SELECT DISTINCT WholesalePrice
FROM Product_Vendors
WHERE Product_Vendors.ProductNumber = Products.ProductNumber
AND WholesalePrice = (
SELECT MAX(WholesalePrice)
FROM Product_Vendors
WHERE Product_Vendors.ProductNumber =
Products.ProductNumber)
LIMIT 1)
AND CategoryID = 1;...instead of:
UPDATE Products
SET
RetailPrice = ROUND(1.35 * (SELECT MAX(WholesalePrice)
FROM Product_Vendors
WHERE Product_Vendors.ProductNumber =
Products.ProductNumber),0)
WHERE RetailPrice < 1.35 * (SELECT MAX(WholesalePrice)
FROM Product_Vendors
WHERE Product_Vendors.ProductNumber =
Products.ProductNumber
LIMIT 1)
AND CategoryID = 1;两者产生相同的结果,在MySQL Workbench ...so中受影响的行数相同,为什么?谢谢你们。
发布于 2018-06-03 09:01:44
很难猜测作者为什么选择这种形式。也许他们想对相关的子查询提出一点看法。也许他们想避免书中没有介绍的技巧。也许这是他们第一次想到的事情,他们从来没有时间去优化它。也许他们编写的SQL考虑到了某个MySQL版本的功能(我认为以前有一些MySQL版本不能分组子查询)。
这里还有另一种方法。我更喜欢它的清晰性,它很可能也更有效率。
UPDATE
Products
INNER JOIN (
SELECT ProductNumber, MAX(WholesalePrice) * 1.35 as RetailPrice
FROM Product_Vendors
GROUP BY ProductNumber
) Target ON Target.ProductNumber = Products.ProductNumber
SET
Products.RetailPrice = ROUND(Target.RetailPrice, 0)
WHERE
Products.CategoryID = 1
AND Products.RetailPrise < Target.RetailPrice;https://stackoverflow.com/questions/50664581
复制相似问题