繁体   English   中英

使用INNER JOIN两次替换列会得到歧义名称错误

[英]Using INNER JOIN twice to replace columns gets Ambiguous Name Error

我有一张自行车旅行表( bixi_august )和一张自行车停靠站( bixi_stations )表。 bixi_august仅具有站号,并且名称存储在bixi_stations.name

我正在尝试编写一个查询,该查询显示最常见的行程,但显示更具可读性的车站名称,而不是代码。

当我输入以下内容时,出现SQL error or missing database (ambiguous column name: bixi_stations.name)

SELECT bixi_stations.name as 'Start Station', bixi_stations.name as 'End 
Station', COUNT(*)
FROM bixi_august
INNER JOIN bixi_stations ON bixi_august.start_station_code=bixi_stations.code
INNER JOIN bixi_stations ON bixi_august.end_station_code=bixi_stations.code
GROUP BY bixi_august.start_station_code, bixi_august.end_station_code
ORDER BY COUNT(*) DESC;

我基本上是想得到这个,但是表中没有显示站号。

SELECT bixi_stations.name as 'Start Station name', start_station_code, bixi_stations.name as 'End Station', end_station_code, COUNT(*) as 'Total Trips'
FROM bixi_august
INNER JOIN bixi_stations ON bixi_august.start_station_code=bixi_stations.code
GROUP BY start_station_code, end_station_code
ORDER BY COUNT(*) DESC;

我对SQL相当陌生,但Google搜索/搜索并没有帮助我。 我感到自己的问题是在我的select语句中两次拥有bixi_stations.name ,而没有模糊内部联接的工作方式。

您需要表别名来区分表引用:

SELECT ss.name as Start_Station, se.name as End_Station, COUNT(*)
FROM bixi_august a INNER JOIN
     bixi_stations ss
     ON a.start_station_code = ss.code INNER JOIN
     bixi_stations se
     ON a.end_station_code = be.code
GROUP BY ss.name, se.name
ORDER BY COUNT(*) DESC;

注意我对查询所做的更改:

  • 这些表现在具有方便的缩写(称为表别名 )。
  • 别名用于所有引用的列( 合格的列名 )。
  • GROUP BY列与SELECT列相同。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM