[英]How to conditionally Join tables in MySQL Query
Hie,嗨,
I have 3 tables namely Accounts
, Companies
and Freelancers
.我有 3 张表,即
Accounts
、 Companies
和Freelancers
。 The accounts table holds the email
, password
and account_type
fields where if account_type
values is an ENUM('companies','freelancers')
. accounts 表包含
email
、 password
和account_type
字段,如果account_type
值为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
我想知道如果
account_type
字段等于companies
,我如何编写一个加入Companies
表的查询,否则应该加入Freelancers
If you want to get all the data to one table,如果你想把所有数据放到一张表中,
you can simply use a union
to bind 2 results sets that you get from joining 2 tables.您可以简单地使用
union
来绑定从连接 2 个表中获得的 2 个结果集。
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'
You can join the tables according to the ids by getting the ids to one table.您可以通过将 id 获取到一张表来根据 id 加入表。
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.