【MySQL】函数之CONCAT,SUBSTRING
今儿有个需求,需要将某数据库下所有表的表名统一修改一下,表虽然不多,但一个一个的改还是比较low的,而且,重命名的规则也比较统一,就是去掉原有名字的第一个字母。
比较方便的方法是通过SQL生成修改表名的命令,然后批量执行即可。命令如下:
1 |
select CONCAT('alter table ',table_name,' rename to ',SUBSTRING(table_name,2),';') from tables where table_schema = 'database_name'; |
通过这个命令,就可以把指定数据库下所有表的表名重新命名的脚本全部打印出来。
如果是Oracle的话,那就比较方便了,可以写个匿名块,执行一次就全部修改了。
小结:
1:表名数据字典表是information_schema数据库的tables表
2:连接多个字符的函数CONCAT;
语法: CONCAT(str1,str2,…),注意:当多个字符串中只要存在一个null,那么将返回null
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
mysql> select CONCAT('a','b','c',''); +------------------------+ | CONCAT('a','b','c','') | +------------------------+ | abc | +------------------------+ 1 row in set (0.00 sec) mysql> select CONCAT('a','b','c','',null); +-----------------------------+ | CONCAT('a','b','c','',null) | +-----------------------------+ | NULL | +-----------------------------+ 1 row in set (0.00 sec) mysql> |
3:截取字符串SUBSTRING;
语法:SUBSTRING(str FROM pos FOR len)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
## 去掉'Hello World'第一个字母,也就是从第二位起,截取到最后 mysql> select substring('Hello World',2); +----------------------------+ | substring('Hello World',2) | +----------------------------+ | ello World | +----------------------------+ 1 row in set (0.00 sec) mysql> ## 截取'Wo',也就是从第七位起截取2位 mysql> select substring('Hello World',7,2); +------------------------------+ | substring('Hello World',7,2) | +------------------------------+ | Wo | +------------------------------+ 1 row in set (0.00 sec) mysql> ## 截取'World',负数表示从后往前计算数量 mysql> select substring('Hello World',-5); +-----------------------------+ | substring('Hello World',-5) | +-----------------------------+ | World | +-----------------------------+ 1 row in set (0.00 sec) mysql> |