MySQL常见错误汇总

  • Post author:
  • Post category:mysql



1、问题重现:

update stu set score = 80 where id in(select s.id from stu s where sex = 0)


[Err] 1093 - You can't specify target table 'stu' for update in FROM clause


原因:不能在from子句中使用目标表进行更新操作


解决办法如下:

update stu set score = 80 where id in (
select tmp.id from (select s.id from stu s where s.sex = 0)tmp)


2、delete 同时删除多张表,根据数据库的版本来确定是否能用别名


查询数据库版本

select version();


使用别名的写法

delete c,s 
from stu as s
left join class as c on c.stu_id = s.id
where s.id = 2


不使用别名的写法

delete stu,class
from stu
left join class on class.stu_id = stu.id
where stu.id = 3


3、sql_mode = only_full_group_by


问题重现:当数据库开启了only_full_group_by之后,在数据库中执行group by的语句,会报错,因为group by之后的跟的字段没有包含select之后查询的所有的字段。


解决办法1:暂时性解决办法,数据库服务重启如下配置仍会失效

set @@global.sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
set sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';


解决办法2:永久性解决办法,数据库服务重启配置仍然有效,在my.ini文件对应位置[mysqld]加上如下配置

sql_mode =STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION


解决办法3:在无法修改数据库配置的前提下,可以在yaml文件配置数据源的地方加上如下配置.

connectionInitSqls:["set SESSION sql_mode=REPLACE(@@SESSION.sql_mode,'ONLY_FULL_GROUP_BY',"")"]


4、修改系统的默认时区


问题重现:获取服务当前时间存入数据库,存入数据库的时间比当前时间少8个钟


解决办法:

TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));



版权声明:本文为hello_world_9664原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。