在表中找到订单后获取ID

时间:2015-06-28 13:10:39

标签: mysql

我正在尝试使用此查询获取doc/表中最后一个stop_name stop_id的{​​{1}},但我收到此错误GHI虽然我有此列在我的桌子里。

查询1:

stops

当我尝试如下时,我得到了结果。

QUERY2:

Column 'stop_id' in field list is ambiguous

停止表:

SELECT stop_id
FROM stops s1 
JOIN stops s2 ON s1.stop_id = s2.stop_id - 1
JOIN stops s3 ON s2.stop_id = s3.stop_id - 1
WHERE CONCAT(s1.name, s2.name, s3.name) = CONCAT('ABC','DEF','GHI')

简单:

SELECT 1
FROM stops s1 
JOIN stops s2 ON s1.stop_id = s2.stop_id - 1
JOIN stops s3 ON s2.stop_id = s3.stop_id - 1
WHERE CONCAT(s1.name, s2.name, s3.name) = CONCAT('ABC','DEF','GHI')

4 个答案:

答案 0 :(得分:3)

您多次将表连接到自身,并且需要指定要使用的表。在你的情况下,它将是第3个表:

SELECT s3.stop_id
FROM stops s1 
JOIN stops s2 ON s1.stop_id = s2.stop_id - 1
JOIN stops s3 ON s2.stop_id = s3.stop_id - 1
WHERE CONCAT(s1.name, s2.name, s3.name) = CONCAT('ABC','DEF','GHI')

答案 1 :(得分:2)

不明确并不意味着它缺失,它确实意味着您的联接表中有多个可能的列。所以你需要

SELECT table.stop_id ...  

答案 2 :(得分:1)

在语句SELECT stop_id stop_id 中可以引用stops s1stops s2stops s3中的列,因此您必须指定哪个表你想要它,你想要的select s3.stop_id就是GHI

答案 3 :(得分:0)

您需要使用正确的表别名限定select s1.stop_id来限定列,否则会让数据库引擎感到困惑,因为要选择表stops s1stops s2的列,所以错误抛出。

您的查询应该是

SELECT s1.stop_id       <-- see s1 alias added
FROM stops s1 
JOIN stops s2 ON s1.stop_id = s2.stop_id - 1
JOIN stops s3 ON s2.stop_id = s3.stop_id - 1
WHERE CONCAT(s1.name, s2.name, s3.name) = CONCAT('ABC','DEF','GHI')