I have multiple table for a project (sessions , charges and payments)
To get the sessions i’m doing the following :
SELECT
sess.file_id, SUM(sess.rate * sess.length) AS total
FROM
sess
WHERE sess.sessionDone = 1
GROUP BY sess.file_id
This will return the amount that a specific student should pay
I also have another table “charges”
SELECT
file_charges.file_id, SUM(file_charges.price) AS total_charges
FROM
file_charges
GROUP BY file_charges.file_id
And finally the payment query :
SELECT
file_payments.file_id, SUM(file_payments.paymentAmount) AS total_payment
FROM
file_payments
GROUP BY file_payments.file_id
Can i combine those 3 in a way to have :
Total = Payments - (Session + Charges)
Note that it could be negative so i could have file_id that exists in session , charges but not in payments and i could have a payment without sessions or charges …
One issue that needs to be addressed is whether one of these queries can be the “driver”, in cases where we don’t have rows for a given
file_idreturned by one or more of the queries. (e.g. there might be rows fromsess, but none fromfile_payments. If we want to be sure to include every possiblefile_idthat appears in any of the queries, we can get a list of all possiblefile_idwith a query like this:(NOTE: The UNION operator will remove any duplicates)
To get the specified resultset, we can use that query, along with “left joins” of the other three original queries. The outline of the query will be:
In that statement
ais a standin for the query that gets the set of allfile_idvalues (as shown above). Thes,candpare standins for your three original queries, on sess, file_charges and file_payments, respectively.If any of the
file_idvalues is “missing” from any of the queries, we are going to need to substitute a zero for the missing value. We can use the IFNULL function to handle that for us.This query should return the specified resultset:
(The EXPLAIN for this query is not going to be pretty, with four derived tables. On really large sets, performance may be horrendous. But the resultset returned should meet the specification.)
Beware of queries that JOIN all three tables together… that will likely give incorrect results when there are (for example) two (or more) rows for the same
file_idin thefile_paymenttable.There are other approaches to getting an equivalent result set, but the query above answers the question: “how can i get the results of these queries joined together into a total”.
Using correlated subqueries
Here’s another approach, using correlated subqueries in the SELECT list…