我有一个主/细节表安排(一对多),我想要一个主场和一个细节场。
我是否必须运行2个sql语句,或者我可以将它们有效地合并到一个语句中并且仍然不能获得主值的重复总和吗?
样品:
orders:
customer_id int,
order_id int,
order_amount int
details:
customer_id int,
order_id int,
detail_amount int
SELECT sum(order_amount), sum(detail_amount) FROM orders m
JOIN details d on d.order_id = m.order_id
WHERE customer_id = 123;
the results will be incorrect when orders exist with multiple details.
I can:
SELECT sum(order_amount) FROM orders m
WHERE customer_id = 123;
and
SELECT sum(detail_amount) FROM details d
WHERE customer_id = 123;
我可以有效地组合它们吗?
答案 0 :(得分:0)
使用子查询很容易。
SELECT sum(order_amount) as orderTotal, (SELECT sum(detail_amount) FROM details d
WHERE d.customer_id = m.customer_id) as detailTotal FROM orders m
WHERE customer_id = 123;