WEB开发网
开发学院数据库MySQL MySQL4中嵌套子查询删除出错解决方案 阅读

MySQL4中嵌套子查询删除出错解决方案

 2009-10-12 00:00:00 来源:WEB开发网   
核心提示:MySQL4中嵌套子查询做删除操作会出错,例如下面的SQL:deletefrommoviesparamwherempegin(selectmp.mpegfrommoviesmv,moviesparammpwheremv.mpeg=mp.mpeg)执行提示:错误码: 1093 You can't specify

MySQL4中嵌套子查询做删除操作会出错,例如下面的SQL:

delete from moviesparam 
where mpeg in (select mp.mpeg 
                                        from movies mv, moviesparam mp 
                                     where mv.mpeg = mp.mpeg) 

执行提示:

错误码: 1093

You can't specify target table 'moviesparam' for update in FROM clause

原因:所删除表的在子查询中出现,就会出错,当然,此SQL放到MySQL5中执行是没有问题的。

为了解决此问题,可以建立一张临时表,将子查询的数据写入到临时表,然后做子查询删除即可。

当然,此处的临时表并被真是真正意义的临时表,是临时创建一个表,用完后再删除。代码如下:

drop table if exists tmp_del_mp; 
create table tmp_del_mp as 
select mpeg from moviesparam where mpeg not in (select mpeg from movies); 
delete from moviesparam where mpeg in (select mpeg from tmp_del_mp); 
drop table if exists tmp_del_mp;

这样就变相的实现了所要实现的功能。

将上面的SQL放置到JDBC代码中执行:

Statement stmt = conn.createStatement();    
stmt.addBatch("drop table if exists tmp_del_mp");    
stmt.addBatch("create table tmp_del_mp as\n" +    
    "select mpeg from moviesparam where mpeg not in (select mpeg from movies)");    
stmt.addBatch("delete from moviesparam where mpeg in (select mpeg from tmp_del_mp)");    
stmt.addBatch("drop table if exists tmp_del_mp");    
stmt.executeBatch();

出处:http://lavasoft.blog.51cto.com/62575/202000

Tags:MySQL 嵌套 查询

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接