检索基于间接引用的行

时间:2015-10-15 06:50:24

标签: mysql sql

我遇到查询问题。基于主键,我必须在同一元组/行中使用外键来访问外键是主键的另一个表。

我不知道如何解决这个问题,因为我无法将外键保存在变量中。

执行此操作的查询;

 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个查询来做,但我宁愿一个查询。

1 个答案:

答案 0 :(得分: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'