【mysql】二 select * from (select * from table) as table2 使用 与 convert、cast的String转INT使用

版权声明:转载请标明出处。 https://blog.csdn.net/u010720408/article/details/88846803

需求:

查询某列最大值+1,做为新纪录的列值(分布式环境,一条语句实现)

问题一:先查询到最大值+1

select nextCode from (select max(projcode)+1 as nextCode from sm_sys_project where syscode=‘000’ ) as t

要点:取别名 as tableName (略取as也可)
eg:
select max+1 from (select max(projcode) as max from sm_sys_project where syscode=‘000’ ) t
也能实现

问题二:projcode列是String ,select ‘9’>‘10’ 是1为真,会报主键重复

需要String 转 int
三种方式:
①String + int 转int
select ‘9’+0>‘10’+0
结果:0 假

②cast( String as INT)
select cast(‘9’ as UNSIGNED) > cast(‘10’ as UNSIGNED)
结果:0 假

③convert(String , INT)
select convert(‘9’,UNSIGNED) > convert(‘10’,UNSIGNED)
结果:0 假

三者性能懒得测了,也不是频繁触发的语句

最终测试语句

set @name=“projectname”;
insert into sm_sys_project (syscode,sysname,projcode,projname)
select ‘0000’,‘all’,(select max(projcode+1) as nextCode from sm_sys_project),@name
from dual
where not exists( select * from sm_sys_project where projname=@name);

把max(projcode)+1 变成max(projcode+1)即可,如果表数据量大,要注意性能测试再选择String to int的方式

最终实现code列取最大+1,且projname纪录不存在的情况下才新增

猜你喜欢

转载自blog.csdn.net/u010720408/article/details/88846803