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

n6lpvg4x  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(277)

我已经写了一个sql查询,但我不知道它是不是最好的。
我有两张table,关系是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'
lnxxn5zx

lnxxn5zx1#

可以避免子查询;并使用 Inner join 在两张table之间,使用 Group byHaving .
请尝试以下操作:

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

相关问题