0

我有一个包含两个表、链接和旅游的数据库。旅游定义为

+----+-------------+-----+-----+--------+---------+-------+---------+
| ID | FileName    | Lat | Lon | Name   | Heading | Width | Height  |
+----+-------------+-----+-----+--------+---------+-------+---------+

和链接被定义为

+-----+------------+--------+
| ID  | locationID | linkID |
+-----+------------+--------+

links.locationID是 tour.ID 的外键。我想要做的是获取与特定链接匹配的所有链接tour.name

现在,我必须运行这两个查询,并使用第一个的 ID 作为第二个的变量

SELECT * FROM tour WHERE tour.name = 'name'

SELECT * FROM tour
  INNER JOIN links ON tour.ID = links.linkID 
  WHERE links.locationID = ID of first query

我怎样才能使它适应一个单一的搜索?

我试过一个子查询:

SELECT * FROM tour 
  INNER JOIN links ON tour.ID = links.linkID 
  WHERE links.locationID = ( SELECT * FROM tour WHERE tour.name = 'name')

这给了我一个错误 1241,说操作数应该包含一列。

我查找了一些子查询的示例,但是它们都缺少我正在使用的内部连接语句。此查询需要进行哪些修改?

4

1 回答 1

1
SELECT links.*, tour.*
FROM links
JOIN tour ON tour.ID = links.linkID
JOIN tour AS location ON location.ID = links.locationID -- you must create an alias, in order to refer to this table without ambiguity
WHERE location.name = 'name';

至于您的带有子查询的版本,您可以这样做:

SELECT * FROM tour 
INNER JOIN links ON tour.ID = links.linkID 
WHERE links.locationID = (
    SELECT ID -- "operand should contain one column"
    FROM tour WHERE tour.name = 'name'
);

但更喜欢第一种选择。

于 2012-06-28T20:05:24.487 回答