mysql的deletefrom和update⼦查询限制
最经做项⽬时发现的问题,好像在update时也有。。。
⽹上查到的资料如下:
1.使⽤mysql进⾏delete from操作时,若⼦查询的 FROM 字句和更新/删除对象使⽤同⼀张表,会出现错误。
mysql> DELETE FROM tab1 WHERE col1 = ( SELECT MAX( col1 ) FROM tab1 );
ERROR 1093 (HY000): You can’t specify target table ‘tab1′ for update in FROM clause
针对“同⼀张表”这个限制,撇开效率不谈,多数情况下都可以通过多加⼀层select 别名表来变通解决,像这样
DELETE FROM tab1
WHERE col1 = (
SELECT MAX( col1 )
FROM (
SELECT * FROM tab1
) AS t
);
或这样
delete from theTable where id in
(
select id from
(
select min(id) id from theTable group by title HAVING count(*)>1
) ids
)
;
------------------------------------------------------------------------
2. mysql delete from where in 时后⾯的查询语句⾥不能加where条件
Sql代码
delete from `t_goods` where fi_id in (select * from ( select fi_id from `t_goods` where fs_num is null and fs_name is null and fs_type is null and fs_using is null and fs_lifetime is null) b)
Sql代码
delete from `t_goods` where fi_id in (select fi_id from `t_goods` where fs_num is null and fs_name is null and fs_type is null and
fs_using is null and fs_lifetime is null)
Sql代码
delete from `t_goods` where fi_id in ( select fi_id from `t_goods` )
mysql中delete语句上⾯三种情况,只有中间的不能执⾏。
综合起来就是mysql delete from where in 时后⾯的查询语句⾥不能加where条件
---------------------------------------------------------------------------
3. delete 这其中table不能使⽤别名
Sql代码
delete from student a where a.id in (1,2);(执⾏失败)
select a.* from student a where a.id in (1,2);(执⾏成功)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论