基于此表架构:
products
+----+------+-------+--------+--------------+-------+-------+------+-------+
| Id | Name | Price | Detail | Product_type | Image | Color | Size | Stock |
+----+------+-------+--------+--------------+-------+-------+------+-------+
order_details
+----+------------+--------+------+-------+----------+
| Id | Product_id | Amount | Size | Color | Order_id |
+----+------------+--------+------+-------+----------+
orders
+----+-----------+------------+----------+
| Id | Client_id | Date_start | Date_end |
+----+-----------+------------+----------+
如何选择指定客户和订单 ID 的 products.Price * order_details.Amount
的 SUM()
(如果有必要的话)?
我尝试过此查询,其中包括:
SELECT SUM((SELECT pr.Price FROM products pr WHERE pr.Id = od.Product_id) * od.Amount) AS Total
FROM order_details od
WHERE (SELECT o.Client_id FROM orders o WHERE o.Id = $order) = $client
但它返回了错误的结果,我不知道该怎么做。另请注意我想使用子查询。
谢谢。
最佳答案
不使用子选择,使用联接:
SELECT orders.Id, SUM(products.Price * order_details.amount)
FROM orders
LEFT JOIN orders_details ON orders.Id = order_details.Order_id
LEFT JOIN products ON products.Id = order_details.Product_id
GROUP By orders.Clien_id, orders_details.Product_id
关于mysql - 如何选择两个不同表字段的乘积和指定其他两个字段的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27178277/