Sql 按一个客户选择所有订单
我有三个表,Sql 按一个客户选择所有订单,sql,Sql,我有三个表,订单,订单详情和客户。我需要为orders表选择一个客户的订单,所以我这样做了 订单列: id customer_id created vat discount amount paid id order_id cost qty product 订单\u详细信息列: id customer_id created vat discount amount paid id order_id cost qty product 我使用的SQL SELECT orders.*,
订单
,订单详情
和客户
。我需要为orders
表选择一个客户的订单,所以我这样做了
订单
列:
id
customer_id
created
vat
discount
amount
paid
id
order_id
cost
qty
product
订单\u详细信息
列:
id
customer_id
created
vat
discount
amount
paid
id
order_id
cost
qty
product
我使用的SQL
SELECT
orders.*,
SUM(orders_details.qty*orders_details.cost) as amount,
SUM(orders_details.qty) AS qty
FROM
orders,
orders_details,
customers
WHERE
orders.customer_id = customers.id
AND orders_details.order_id = orders.id
AND orders.customer_id = 1
但是我得到的是一个错误的数量30而不是20,并且数量是错误的您缺少了一个
GROUP BY
子句,我猜它应该在orders.id
上 如果要按订单进行聚合,则需要一个GROUP BY
子句。另外,您也可以考虑使用别名使查询更加紧凑。
SELECT
o.*,
SUM(od.qty * od.cost) AS amount,
SUM(od.qty) AS qty
FROM orders o
INNER JOIN orders_details od ON od.order_id = o.id
INNER JOIN customers c ON o.customer_id = c.id -- not used, might be excluded
WHERE o.customer_id =1
GROUP BY o.id
根据您使用的数据库系统,您可能需要将o.*中引用的所有列包含在组中,具体取决于:
GROUP BY o.id, o.customer_id, o.created, o.vat, o.discount, o.amount, o.paid
最后一点注意:由于您似乎没有使用customers表中的任何数据,您可能可以完全排除该表。我认为您应该使用GROUP BY on orders.id-在ANSI-92 SQL标准(20多年前)中,旧样式的逗号分隔表样式被正确的ANSIJOIN
语法所取代而且不鼓励使用它