I have three tables:
- customers: id, name
- contracts_jewels: id, customer_id, paid, transferred, final_date
- contracts_objects: id, customer_id, paid, transferred, final_date
As you see, the structure of the last two tables is the same. The "paid" and the "transferred" fields contain the value 0 or 1.
What I need is to make a query which should return all the clients (no matter if they have contracts or not), and for each client: id, name, count_contracts_all, count_contracts_active
where:
- count_contracts_all would mean the sum of [SELECT COUNT( * ) FROM contracts_jewels WHERE customer_id=3 (for example)] and [SELECT COUNT( * ) FROM contracts_objects WHERE customer_id=3 (for example)]
- count_contracts_active would mean the sum of [SELECT COUNT( * ) FROM contracts_jewels WHERE customer_id=3 AND final_date>=Now() AND paid=0 AND transferred=0] and [SELECT COUNT( * ) FROM contracts_objects WHERE customer_id=3 AND final_date>=Now() AND paid=0 AND transferred=0]
Any idea? Would you please help me? Thank you!
SELECT field_1[, field_2,…] FROM table_1[, table_2,…] UNION [ALL] SELECT field_a[, field_b,...] FROM table_a[, table_b,…];