问题背景:
一个task表,代表的是任务,其中包含id(任务id)、pid(上级任务id)、eid(员工id)等。
还有个employee表,代表的是员工,其中包含id(员工id)等。
三表连接:task(t1)、task(t2)、employee(emp)
根据t1中的pid去连接t2,根据t1中的eid去连接emp。
(还会根据其他条件筛选t1中的记录,连接条件不满足也保留t1中的记录)
问题描述:
我的sql语句:
select t1.* from task t1 left outer join task t2 LEFT OUTER JOIN employee emp
where t1.eid = emp.id and t1.pid = t2.id
phpMyAdmin错误如下:
SQL 查询:
select t1.* from task t1 left outer join task t2 LEFT OUTER JOIN employee emp
where t1.eid = emp.id and t1.pid = t2.id LIMIT 0, 25
MySQL 返回: 文档
#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your
MySQL server version for the right syntax
to use near 'where t1.eid = emp.id and t1.pid = t2.id LIMIT 0, 25'
at line 2
问题分析:
是在'where'附近报错,所以将'where'改为'on',经过验证,下面的sql语句是可以正常执行的:
select t1.* from task t1 left outer join task t2
on t1.eid = emp.id
但是,下面的语句:
select t1.* from task t1 left outer join task t2 LEFT OUTER JOIN employee emp
on t1.eid = emp.id and t1.pid = t2.id
仍旧报错:
SQL 查询:
select t1.* from task t1 left outer join task t2 LEFT OUTER JOIN employee emp
on t1.eid = emp.id and t1.pid = t2.id LIMIT 0, 25
MySQL 返回
#1064 - You have an error in your SQL syntax;
check the manual that corresponds to your MySQL
server version for the right syntax to use near 'LIMIT 0, 25'
at line 2
解决方案:
在'limit'附近报错,我并没有使用limit语句,应该是系统自动添加的limit语句。
'near...',...的附近,是重要的参考信息,'limit'是系统在我写的sql语句的末尾自动添加的,所以应该是在语句末尾有错。
语句末尾有什么?什么也没有,所以自动添加'limit'。
不能具体到语句中的某一处,是不是说明语法错误比较大?三表连接的语法是什么
最终确认,下面的语句是正确的:
select t1.* from (task t1 left outer join task t2 on t1.pid = t2.id )
left outer join employee emp on t1.eid = emp.id