我有一个包含两个表,链接和巡视的数据库。游览被定义为
+----+-------------+-----+-----+--------+---------+-------+---------+
| 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,说操作数应该包含一列。
我查了一些子查询的例子,但是他们都缺少我正在使用的内部连接语句。此查询需要进行哪些修改?
答案 0 :(得分: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'
);
但更喜欢第一种选择。