2015-10-15 57 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'