当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
数据库辅导:MySQL4中嵌套子查询删除出错解决方案
发布时间:2010/1/15 20:30:07 来源:城市学习网 编辑:海蓝

  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();

广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved