首页 > 更安全的执行INSERT INTO TABLE1 SELECT * FROM TABLE2 WHERE...

更安全的执行INSERT INTO TABLE1 SELECT * FROM TABLE2 WHERE...

在mysql的存储过程中执行:

insert into table1
select * from table2
where xxxx=xxxx

table1table2的结构是一样的

但是select * from table2 where ...的结果有时候是空的
这时插入table1,就会出现Column 'ID' cannot be null的错误

请问有什么更加安全做法,如果查询的结果是空就不执行插入,MySQL有提供相关的支持么?

[补充]
上面是个归档的存过,归档之后还需要执行删除操作:

insert into month_table
select * from day_table
where xxxx=xxxx;

delete from day_table where xxxx=xxxx;

这时候出现了Dead lock found when try get lock; try restarting transaction的错误。
是不是因为insert into select...语句出错但并没有释放锁?


请问有什么更加安全做法,如果查询的结果是空就不执行插入,MySQL有提供相关的支持么?

我如果遇到这个问题,还不会去费尽心思想insert into table1 select * from table2 where xxxx=xxxx mysql有没有对这种语法的保护(没有数据不插入),想要这个小判断为什么不自己提前查一下有没有数据呢?用count, limit 1

但是select * from table2 where ...的结果有时候是空的
这时插入table1,就会出现Column 'ID' cannot be null的错误

然后说这个,记忆中不会因为空集报错的,所以特地写了PROCEDURE试了下,如果查询的是空结果集不会报错,"Column 'ID' cannot be null"这个错误应该是ID不允许为空,但你要插入的是空,检查下吧

这时候出现了Dead lock found when try get lock; try restarting transaction的错误。
是不是因为insert into select...语句出错但并没有释放锁?

个人觉得不是,请先把上面插入改正确后看是否还有锁提示,查看mysql的连接看是谁在锁这个表

【热门文章】
【热门文章】