简体   繁体   中英

Join three tables using conditional joins in MySQL

I'm trying to modify and existing query to work with a conditional JOIN.

I have three tables: invoices , companies and clients .

The application logic is this: first there's a bill of quantities which gets created for each order. Then, I create an invoice for that bill of quantities. Sometimes the client that makes the order is different from the client that gets billed (example: client A from company A+ is making an order, but client B from company B+ is getting billed for that order). For this scenario I have the invoice_as_company_id and invoice_as_client_id columns.

Right now I have a query that gets all the invoices and it looks like this:

SELECT i.*, co.name AS company, cl.name AS client
FROM invoices i
LEFT JOIN companies co ON i.invoice_company_id = co.company_id
LEFT JOIN clients cl ON i.invoice_client_id = cl.client_id
ORDER BY i.invoice_date DESC
LIMIT 10

So I would like to modify this query like this:

  • if the invoice_as_company_id is null, the use the invoice_company_id field in the companies table join
  • if the invoice_as_client_id is null, the use the invoice_client_id field in the clients table join

The database tables are bellow.

Invoices

+-----------------------+--------------+
| invoice_id            | int(10)      |
| invoice_date          | date         |
| invoice_number        | int(11)      |
| invoice_amount        | decimal(5,2) |
| invoice_company_id    | int(11)      |
| invoice_client_id     | int(11)      |
| invoice_as_company_id | int(11)      |
| invoice_as_client_id  | int(11)      |
| date_added            | int(11)      |
+-----------------------+--------------+

Companies

+--------------+--------------+
| company_id   | int(10)      |
| company_name | varchar(255) |
| date_added   | int(11)      |
+--------------+--------------+

Clients

+-------------+--------------+
| client_id   | int(10)      |
| client_name | varchar(255) |
| date_added  | int(11)      |
+-------------+--------------+

LEFT JOIN companies co ON co.company_id=IFNULL(i.invoice_company_as_id, i.invoice_company_id)

And if you have more specific test cases:

LEFT JOIN companies co ON co.company_id=IF(i.invoice_company_as_id IS NULL OR i.invoice_company_as_id = 0, i.invoice_company_as_id, i.invoice_company_id)

Same for your 2nd case. Performances may go away for heavy tables...

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