我写了一个SQL查询,但是我不知道它是不是最好。
我有两个表,关系是1-n。
订单表
|---------------------|
| orderNumber |
|---------------------|
| status |
|---------------------|
orderDetail
|---------------------|
| orderNumber |
|---------------------|
| quantity |
|---------------------|
| price |
|---------------------|
我要获取状态为shipped
的订单,并且totalPrice大于1500并且totalPrice排序下降
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'
答案 0 :(得分:1)
您可以避免子查询;并使用两个表之间的variable
以及Inner join
和Group by
来解决此问题。
尝试以下操作:
Having