MySQL内部连接查询语法错误

时间:2013-08-22 20:27:32

标签: mysql

我是一个MySQL新手,无法弄清楚这里出了什么问题。我有两张桌子。左表称为锻炼。相关列为date(类型日期)和id(类型为int)。

右表名为Workout_locations(相关字段:workout_id type int, and location_id type int)。

加入字段为Workouts.idWorkout_locations.workout_id

我想要做的就是获得两列的表格:date(来自锻炼)和location_id(来自Workout_locations)。我只需要根据几个字段从Workouts表中提取记录(sql语句应该明确这一点)。

这是我的sql语法:

SELECT Workouts.date as date, Workout_locations.location_id as loc_id
FROM Workouts 
WHERE Workouts.pacegroup_id='9' AND (Workouts.date BETWEEN '2013-08-19' AND '2013-08-25') 
INNER JOIN Workout_locations ON Workouts.id=Workout_locations.workout_id"

但是我收到了这个错误:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'INNER JOIN Workout_locations ON   第1行的Workouts.id = Workout_locations.workout_id'

我希望对于有这方面经验的人来说,这是一个非常容易发现的错误。谁能看到它?谢谢!

1 个答案:

答案 0 :(得分:3)

您的INNER JOIN应该出现在WHERE之前。我也不认为你需要parens around your BETWEEN clause,但我怀疑它会导致错误:

SELECT Workouts.date as date, Workout_locations.location_id as loc_id 
FROM Workouts 
INNER JOIN Workout_locations ON Workouts.id=Workout_locations.workout_id
WHERE Workouts.pacegroup_id = '9' 
AND Workouts.date BETWEEN '2013-08-19' AND '2013-08-25';

此外,虽然他们技术上让你逃脱它,但你应该避免使用" date"作为选定的列名称(它是reserved word)。

你也可以做一些精简,让事情更容易阅读:

SELECT Workouts.date AS wo_date, Workout_locations.location_id AS loc_id
FROM Workouts w
INNER JOIN Workout_locations l ON w.id = l.workout_id
WHERE w.pacegroup_id = '9'
AND w.date BETWEEN '2013-08-19' AND '2013-08-25';