2015-10-15 51 views
-1

我有一個查詢的麻煩一行。根據主鍵,我必須在同一個元組/行中使用外鍵來訪問外鍵是主鍵的另一個表。基於檢索間接引用

我不知道如何解決這個問題,因爲我無法將外鍵保存在變量中。

tldr查詢做到這一點;

1. Use user input to search for primary key 
2. Get requested row 
3. Use a column in that row to search for another table 
4. Get Second requested row 
5. Return all contents from the 2 rows requested. 

SELECT * from table1 where table1.primaryKey = 'userInput' 
UNION 
SELECT * from table2, table1 where table1.foreignKey = table2.foreignKey; 

這是我到目前爲止,但它不起作用。但它說明了我的觀點。

通常我會用2個查詢來做,但我寧願一個一個地做。

+0

使用2個查詢之間的連接 – Mihai

回答

1

有關使用JOIN是幾?

SELECT * 
FROM table2 
    JOIN table1 
    ON table1.foreignKey = table2.foreignKey 
WHERE table1.primaryKey = 'userInput' 

或者另一種方式來做到這一點是:

SELECT * 
FROM table1, table2 
WHERE table1.foreignKey = table2.foreignKey 
     AND table1.primaryKey = 'userInput'