[英]How to conditionally Join tables in MySQL Query
嗨,
我有 3 張表,即Accounts
、 Companies
和Freelancers
。 accounts 表包含email
、 password
和account_type
字段,如果account_type
值為ENUM('companies','freelancers')
。 我想知道如果account_type
字段等於companies
,我如何編寫一個加入Companies
表的查詢,否則應該加入Freelancers
如果你想把所有數據放到一張表中,
您可以簡單地使用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'
您可以通過將 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'
我希望這將幫助您解決您的問題。
例如
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.