簡體   English   中英

在單個查詢中將表連接到其他兩個表

[英]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_ctable_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_btable_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


更新如果您不只想要您描述的table_b和table_c中first_column常見的行,請嘗試以下操作:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM