我一直在努力寻找能够更好地满足我特定需求的例子,但我似乎找不到任何例子。
我有以下SQL语句,它就像一个魅力:
SELECT
customers.id,
customers.customer_name,
SUM(shipments.balance) AS shipmentBalance
FROM customers
LEFT JOIN shipments ON customers.id = shipments.bill_to
GROUP BY customers.id, customers.customer_name
ORDER BY shipmentBalance DESC;
但是,我希望能够在JOIN中添加where条件,因为我不希望所有的货运余额都被提升,而只是那些余额大于相关支付分配金额的货币。
此时,在单独的查询中,我可以使用以下查询提取余额大于其付款分配金额的货件:
SELECT
shipments.id,
shipments.pro_number,
shipments.balance,
SUM(payments_distributions.amount) AS Sum
FROM
shipments
LEFT JOIN payments_distributions ON shipments.pro_number = payments_distributions.shipment_id
WHERE balance > (SELECT IFNULL(SUM(payments_distributions.amount),0) FROM payments_distributions WHERE payments_distributions.shipment_id = pro_number)
GROUP BY shipments.id,shipments.pro_number;
但我不确定如何将它们结合起来。
答案 0 :(得分:1)
将Shipment表的过滤器放在ON子句中:
SELECT
customers.id,
customers.customer_name,
SUM(shipments.balance) AS shipmentBalance
FROM customers
LEFT JOIN shipments ON customers.id = shipments.bill_to
AND balance > (SELECT IFNULL(SUM(payments_distributions.amount),0)
FROM payments_distributions
WHERE payments_distributions.shipment_id = pro_number)
GROUP BY customers.id, customers.customer_name
ORDER BY shipmentBalance DESC;