Hopefully I can do this without writing a book… I’m working on a system for a Surveying company. They’re also throwing in an accounting section, and one of the functionalities it needs is to find jobs that are not completely paid off.
A few points to be made:
- A ‘job’ is a project, essentially. There are different types of surveys.
- A job can have more than one “type” of survey in it, thus having more than one price that is calculated into the job’s total price.
- Payments are made on individual jobs (the client might send 30 checks if they have 30 jobs, it’s an accounting thing)
- Job types are dynamic (they can create/delete them from the system panel) – so I can’t hardcode these things
Here’s the applicable database structure:
table jobs: job_id, client_id
table job_types: type_id, type_name
table job_type_assoc: id_job, type_id, price
table payments: payment_id, job_id, amount
Note: payments aren’t made on each job type, but the JOB as a whole (again, as opposed to the client’s account having a “balance”).
I need to somehow pull jobs where the total of price from job_type_assoc is less than the total of amount in payments.
I don’t know if this is possible in mysql alone or if php would be more efficient – also, their old system has about 340,000 jobs in it. Granted that they won’t have the accounting info from then, they do have a lot of work and the new entries will build quickly, AND if I somehow do it in PHP where I end up querying the jobs table a lot, it might get messy.
One possible way you can do this is with a clever combination of subqueries.
This shouldn’t be too bad a query to run, if you have properly indexed job_type_assoc and payments.
Please note that I haven’t tested this exact query, so it might need tweaking. I’ve run the same query against tables on my local DB.