【问题标题】:Alternative for Subquery Other Than a View视图以外的子查询的替代方案
【发布时间】:2017-03-07 03:35:08
【问题描述】:

感谢您查看我的帖子,感谢您提供任何帮助/指导。我缺乏 SQL 技能,我尝试了几种解决方案但均未成功。无论如何,我需要为以下查询创建一个 VIEW:

CREATE VIEW open_orders AS
SELECT
 t1.orderID,
 DATE_FORMAT(t1.orderDate,'%m-%d-%Y') AS orderDate,
 t6.colorName,
 t1.originID,
 t1.rackNumber,
 t2.locationNumber AS originNumber,
 t2.locationName AS originName,
 t3.locationName AS destinationName,
 t4.locationStatusName,
 COUNT(t5.orderID) AS totalCount
FROM `order` AS t1
JOIN `location` AS t2 ON t1.originID = t2.locationID
JOIN `location` AS t3 ON t1.destinationID = t3.locationID
JOIN `locationStatus` AS t4 ON t1.locationStatusID = t4.locationStatusID
LEFT JOIN (SELECT * FROM `orderItem` WHERE `productStatusID` = 02 OR `productStatusID` = 03) AS t5 ON t1.orderID = t5.orderID
JOIN `color` AS t6 ON t1.requestedColorID = t6.colorID
WHERE t1.orderStatusID = 01
GROUP BY t1.orderID
ORDER BY t1.orderDate DESC, t1.orderID DESC;

问题出在子查询上。因为我不能在 FROM 语句中使用子查询,所以我尝试使用 VIEW。但是,表很大,这种方法会导致过多的性能问题。

我确信有一种方法可以在不使用 VIEW 或子查询的情况下完成此任务,但在想出解决方案时遇到了麻烦。

感谢任何帮助/指导。

【问题讨论】:

    标签: mysql sql database view subquery


    【解决方案1】:

    您不需要子查询。

    ...
    LEFT JOIN orderItem AS t5
           ON t5.orderID = t1.orderID
          AND t5.productStatusID IN (02,03)
    JOIN color ...
    

    这与您的查询执行相同的操作,但更有效,因为它避免了派生表。

    【讨论】:

    • 完美!非常感谢迈克尔!!
    猜你喜欢
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 2011-08-01
    相关资源
    最近更新 更多