我有这张桌子
订单
制品
客户
发票
和SQL Join Table
$sql="SELECT customer_name, article_name, orders_id, article_price, order_qty, invoices_id FROM orders LEFT JOIN articles ON order_article_id = articles_id
LEFT JOIN invoices ON order_invoice_id = invoices_id
LEFT JOIN customers on order_customer_id = customers_id";
从这个查询我需要得到的是这个结果示例
是否可以在MySQL中执行此操作,或者我需要一些额外的PHP代码?
答案 0 :(得分:2)
您需要一个聚合查询:
SELECT c.customer_name, i.invoices_id,
sum(order_qty * a.article_price) as amount
FROM orders o LEFT JOIN
articles a
ON o.order_article_id = a.articles_id LEFT JOIN
invoices i
ON o.order_invoice_id = i.invoices_id LEFT JOIN
customers c
on o.order_customer_id = c.customers_id
GROUP BY c.customer_name, i.invoice_id;
请注意,我已添加表别名以更好地指定列的来源。这使查询更容易理解。