2011-03-15 61 views
1
Table1: ID,Name,some more columns 
Table2: ID 
Table3: Name 

我想從table1獲得輸出,其ID是存在於Table2.IDs &其名稱存在於Table3.Name中。合併多個表

換句話說,選擇所有3個表格中存在的數據。

對於前:

表1:

1 John 
2 Will 
3 Michael 

表2:

1 

表3:

Will 

輸出應該是

1 John 
2 Will 
+0

您的輸出顯示2行,但table2沒有ID 2,而table3沒有名稱Will - 您是否要求**數據存在於所有3個表**中?這是含糊不清的。 – Konerak 2011-03-15 20:04:09

回答

2

您需要使用JOIN。

你的描述和你的示例輸出不匹配,所以我給你舉個例子。

根據您的描述,應該是2的內部聯接:

select table1.id, table1.name 
from table1 
inner join table2 on table2.id = table1.id 
inner join table3 on table3.name = table1.name 

根據你的輸出,它應該是2 OUTER與WHERE子句指定了2的至少一個加入滿意連接:

select table1.id, table1.name 
from table1 
left outer join table2 on table2.id = table1.id 
left outer join table3 on table3.name = table1.name 
where table2.id is not null or table3.name is not null 
+0

對INPUT/OUTPUT差異有很好的理解。明確回答含糊不清的問題。 – Konerak 2011-03-15 20:03:09

+0

謝謝,我會將此標記爲答案,但查詢需要很長時間(儘管表格已編入索引),有什麼方法可以提高此查詢的速度嗎? – Sharpeye500 2011-03-15 21:10:39

+0

您正在使用哪種查詢?內部連接還是外部連接? – 2011-03-15 21:19:40

0

根據您的預期結果,看起來您希望Table1中的行匹配Table2或Table3,因此您需要使用LEFT JOIN。

select t1.ID, t1.Name 
    from Table1 t1 
     left join Table2 t2 
      on t1.ID = t2.ID 
     left join table3 t3 
      on t1.Name = t3.Name 
    where t2.ID is not null 
     or t3.Name is not null