简体   繁体   中英

How to conditionally Join tables in MySQL Query

Hie,

I have 3 tables namely Accounts , Companies and Freelancers . The accounts table holds the email , password and account_type fields where if account_type values is an ENUM('companies','freelancers') . I want to know how I can write a query that Joins with Companies Table if account_type fields is equal to companies else should Join with Freelancers

If you want to get all the data to one table,

  1. you can simply use a union to bind 2 results sets that you get from joining 2 tables.

     SELECT * FROM users Accounts a LEFT JOIN Companies c ON c.account_id = a.id WHERE a.account_type = 'companies' UNION SELECT * FROM users Accounts a LEFT JOIN Freelancers f ON f.account_id = a.id WHERE a.account_type = 'freelancers'
  2. You can join the tables according to the ids by getting the ids to one table.

     SELECT Accounts.id, Accounts.type, Companies.account_id AS id2, Freelancers.account_id AS id3 FROM Accounts LEFT JOIN Companies ON Accounts.id = Companies.account_id AND Accounts.type = 'companies' LEFT JOIN Freelancers ON Freelancers.account_id = Accounts.id AND Accounts.type = 'freelancers'

I hope this will help you to resolve your issue.

For example

SELECT Accounts.column1, 
       COALESCE(Companies.column2, Freelancers.column3), -- common column
       Companies.column4,                                -- specific column
       Freelancers.column5                               -- specific column
FROM Accounts
LEFT JOIN Companies ON Companies.account_id = Accounts.id 
                   AND Accounts.account_type = 'companies'
LEFT JOIN Freelancers ON Freelancers.account_id = Accounts.id 
                   AND Accounts.account_type = 'freelancers'

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