首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >仅供凡人使用的SQL第4版-更新数据集

仅供凡人使用的SQL第4版-更新数据集
EN

Stack Overflow用户
提问于 2018-06-03 08:27:46
回答 1查看 222关注 0票数 0

我正在阅读这本书,在第15章中更新数据集,在需要您解决的问题部分中,有以下问题:

将配件零售价格(类别= 1)设置为价格最高的供应商的批发价加上35 %

我有点不明白为什么作者要给出这个解决方案:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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中受影响的行数相同,为什么?谢谢你们。

销售订单修改模式

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-03 09:01:44

很难猜测作者为什么选择这种形式。也许他们想对相关的子查询提出一点看法。也许他们想避免书中没有介绍的技巧。也许这是他们第一次想到的事情,他们从来没有时间去优化它。也许他们编写的SQL考虑到了某个MySQL版本的功能(我认为以前有一些MySQL版本不能分组子查询)。

这里还有另一种方法。我更喜欢它的清晰性,它很可能也更有效率。

代码语言:javascript
复制
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;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50664581

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档