代码之家  ›  专栏  ›  技术社区  ›  ToujouAya

这个查询必须是最优的吗?如果不是的话,还有什么可以改进这个问题吗

  •  1
  • ToujouAya  · 技术社区  · 6 年前

    我有两张桌子,关系是1-n。

    |---------------------|
    |      orderNumber    | 
    |---------------------|
    |          status     |
    |---------------------|
    

    订单详细信息

    |---------------------|
    |      orderNumber    | 
    |---------------------|
    |          quantity   |
    |---------------------|
    |       price         |
    |---------------------|
    

    我想得到订单,状态是 shipped 总价格大于1500,总价格呈下降趋势

    SELECT * FROM order JOIN 
           (Select sub1.orderNumber, SUM(sub1.totalEach) AS total FROM (
              select (quantity * price) AS totalEach, orderNumber FROM orderDetail)
          AS sub1 GROUP BY sub1.orderNumber HAVING total > 1500 ORDER BY total DESC
          ) AS sub2 
          ON order.orderNumber = sub2.orderNumber 
          WHERE order.status = 'shipped'
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Madhur Bhaiya    6 年前

    可以避免子查询;并使用 Inner join 在两张桌子之间,使用 Group by 具有 Having .

    请尝试以下操作:

    SELECT o.orderNumber, 
           o.status, 
           SUM(od.quantity * od.price) AS total   
    FROM order AS o 
    JOIN orderDetail AS od ON o.orderNumber = od.orderNumber 
    WHERE o.status = 'shipped' 
    GROUP BY o.orderNumber, o.status 
    HAVING total > 1500 
    ORDER BY totalEach DESC