2011-08-27 120 views
0

我想用(ID_1)ID的數組從TABLE_1選擇從TABLE_2得到所有行ID_2 = ID_1MySQL的子查詢結果陣列

SELECT field_b 
    FROM table_2 
    WHERE id_2 IN (
     SELECT id_1 FROM table_1 WHERE field_a = 1234 
); 

以下是參考比如我的表:

mysql> select * from table_1; 
    +-------+---------+ 
    | id_1 | field_a | 
    +-------+---------+ 
    |  1 | 1234 | 
    +-------+---------+ 
    |  2 | 1234 | 
    +-------+---------+ 


mysql> select * from table_2; 
+---------+---------+ 
| id_2 | field_b | 
+---------+---------+ 
|  1 | 5678 | 
+-------+-----------+ 
|  2 | 0013 | 
+-------+-----------+ 
+2

你想進行簡單的INNER JOIN? SELECT * from table_2 INNER JOIN table_1 on table_1.id_1 = table_2.id_2?你可以添加任何你想要的條件,例如WHERE field_a = 1234 – mkk

+3

你使用'IN'發佈的代碼應該可以工作... –

+0

@Martin現在你提到它是個好主意。我想知道OP實際上有什麼麻煩? – jadarnel27

回答

3

會的INNER JOIN很好的工作順利嗎?

SELECT field_b 
FROM table_2 
INNER JOIN table_1 
    ON table_2.id_2 = table_1.id_1 
WHERE table_2.field_a=1234 
1

我不知道這是否是你所需要的:

SELECT * FROM table_2 t2 
INNER JOIN table_1 t1 
ON t2.id_2 = t1.id_1 
WHERE t1.field_a = 1234 
1

另一種選擇:

SELECT field_b 
FROM table_2 
WHERE EXISTS 
     (SELECT * 
     FROM table_1 
     WHERE field_a = 1234 
      AND table_2.id_2 = table_1.id_1 
    )