![](/img/trans.png)
[英]MySQL query issue with left joining a table with the results of two other tables
[英]Joining table to two other tables in single query
我通過以這種方式將它連接到table_b
來從table_a
獲取行:
select ta.* from table_a as ta
inner join table_b as tb on ta.first_column=tb.first_column
where tb.second_column='myvalue';
和,
我通過以這種方式將它連接到table_c
從table_a
獲取行:
select ta.* from table_a as ta
inner join table_c as tc on ta.first_column=tc.first_column
where tc.second_column='myvalue';
如何形成一個查詢以獲取上述查詢的所有行(即上述查詢結果的並集)?
我不想自己做一個Union,而是通過形成一個將table_a
聯接到table_b
和table_c
的查詢來table_c
。
您可以在同一查詢中進行多個聯接。
select ta.*,tb.*,tc.* from table_a as ta
inner join table_b as tb on ta.first_column=tb.first_column
inner join table_c as tc on ta.first_column=tc.first_column
where tc.second_column='myvalue' and tb.second_column='myvalue';
如果您希望同時為兩個表(b和c)的second_column為'myvalue'的所有記錄,則將上面的查詢與where子句中的and
結合使用。
否則,如果您希望至少其中一張表(b或c)的second_column為'myvalue'的所有記錄,則將and
聯合替換為or
。
select distinct ta.* from table_a as ta left join table_b as tb on ta.first_column=tb.first_column left join table_c as tc on ta.first_column=tc.first_column where tc.second_column='myvalue' or tb.second_column='myvalue';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.