Home > Database > Mysql Tutorial > Unknown table ‘a’ in MULTI DELETE的解决办法和说明

Unknown table ‘a’ in MULTI DELETE的解决办法和说明

WBOY
Release: 2016-06-07 16:37:35
Original
1882 people have browsed it

仔细看Mysql-文档(12.2.2. DELETE Syntax)手册应该不会出现这个问题,如果遇到请接着向下看: 在存储过程中,调用: delete a from db1.tb1 a, db2.tb2 b where a.col1 = b.col1 and a.col2 = b.col2; 出现题目中的错误,原因如下: 在mysql中多表联合删除

仔细看Mysql-文档(12.2.2. DELETE Syntax)手册应该不会出现这个问题,如果遇到请接着向下看:
在存储过程中,调用:

delete a from db1.tb1 a, db2.tb2 b where a.col1 = b.col1 and a.col2 = b.col2;
Copy after login

出现题目中的错误,原因如下:
在mysql中多表联合删除时,表别名只能在sql中表关联部分声明。我们应该避免不是表关联部分声明别名,因为这产生歧义的sql,从而产生不是期望的结果,例如在错误的表中删除行,举个例子来说:

DELETE t1 AS a2 FROM t1 AS a1 INNER JOIN t2 AS a2;
Copy after login

对于多个表的删除,表的列表中提到的表别名的引用,使用默认数据库,除非已经明确地指定了一个数据库。例如,如果默认数据库是db1,下面的语句将不会工作,因为不确定的别名a2被认为已经有了db1:

DELETE a1, a2 FROM db1.t1 AS a1 INNER JOIN db2.t2 AS a2WHERE a1.id=a2.id;
Copy after login

除了默认数据库外,为了正确地匹配表的别名,我们必须明确地指定正确的数据库的名字,

DELETE a1, db2.a2 FROM db1.t1 AS a1 INNER JOIN db2.t2 AS a2WHERE a1.id=a2.id;
Copy after login

根据上述理论,我的sql应该这样写:

delete db1.a from db1.tb1 a, db2.tb2 b where a.col1 = b.col1 and a.col2 = b.col2;
Copy after login

还有需要注意的是:
1.如果你为一个表声明了别名,当你指向这个表的时候,就必须使用这个别名,例如:

-- 正确的写法: DELETE t1 FROM test AS t1, test2 WHERE ... -- 错误的写法:DELETE test FROM test AS t1, test2 WHERE ...
Copy after login

2.在多个表联合删除时,不能使用order by 或limit,而单个表的删除时就没有这个限制。
3.当前,我们还不能在删除表的时候,在子查询中select from相同的表。

原文:http://www.cnblogs.com/sunss/archive/2011/01/20/1940306.html

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template