2010-06-13 81 views
1

我有我查詢在所述第二域值43的表和我返回第三字段的值從2個表中選擇在一個單一的查詢

SELECT t1_field3 FROM table1 WHERE t1_field2=43 

this returns 19, 39,73 

t1_id t1_field2 t1_field3 
----- --------- --------- 
1   43  19////    
2   43  39////    
3   43  73//// 
4   73  43 
5   13  40 

然後我分別查詢第二表獲取更多信息

SELECT * FROM table2 WHERE t2_id=t1_field3 

t2_id t2_field2 t2_field3 
----- --------- --------- 
19  value19.2 value19.3 
39  value39.2 value39.3 
73  value73.2 value73.3 

有沒有一種方法可以在同一個查詢中同時使用table1和table2?

回答

1
select * from table2 
where t2_id in (select t1_field3 from table1 where t1_field2=43) 
2

您正在描述一個JOIN。在這種情況下,你不需要明確使用JOIN關鍵字雖然,你可以這樣做:

SELECT table1.t1_field3, table2.* FROM table1, table2 WHERE table1.t1_field2=43 AND table2.t2_id = table1.t1_field3 

或許,這將有助於瞭解不同類型的在某些時候加入;編碼恐怖擁有good post

1

有表達直接加入,以及像這樣的方式:

select table1.t1_field3, table2.* 
    from table1 
    join table2 on table1.t1_field3 = table2.t2_id 
where table1.t1_field2 = 43;