简体   繁体   中英

How to select from one table where difference with (sum) from another table?

I have two tables with following fields:
...

orders.orderID
orders.orderValue

and

payments.orderID
payments.payVal

In payments.payVal there will be incremental payments for each order (many-to-one).
What I need it so select ALL orders from orders where there is payment left (orders.orderValue - ((sum)payments.payVal) > 0 ) .

The only thing I can come up to right now is a (foreach) using the orderID , but I cannot do that for some particular reasons. I also cannot add a column inside table to hold the value for some reasons too.

What I need, is to perform the entire selection in one single SQL Query something that resembles this idea: SELECT * FROM orders WHERE <... each(orderValue - (sum(payVal))) > 0 ...>

SELECT *, SUM(p.payVal) AS TotalPayed
FROM orders o
LEFT JOIN payments p ON o.orderID = p.orderID
GROUP BY o.orderID
HAVING SUM(p.payVal) < o.orderValue

This should provide you with the necessary fields, although I would advise you to select specific fields with this query.

The LEFT JOIN makes sure you get every order, even if there are no payments made yet.

SQL Fiddle

Looks like we came to the same solution,

http://sqlfiddle.com/#!2/9a657/18

SELECT * FROM `orders`
LEFT JOIN `payments` AS p ON `orders`.`orderID` = p.`orderID`
GROUP BY `orders`.`orderID`
HAVING SUM(p.`payVal`) <= 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM