MySQL中常用的拼接语句的小结(代码示例)
本篇文章给大家带来的内容是关于MySQL中常用的拼接语句的小结(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
前言:在MySQL中 CONCAT ()函数用于将多个字符串连接成一个字符串,利用此函数我们可以将原来一步无法得到的sql拼接出来,在工作中也许会方便很多,下面主要介绍下几个常用的场景。
注:适用于5.7版本 低版本可能稍许不同。
1.拼接查询所有用户SELECT DISTINCTCONCAT('User: '',USER,''@'',HOST,'';') AS QUERYFROMmysql.USER;# 当拼接字符串中出现'时 需使用转义符2.拼接DROP tableSELECTCONCAT('DROP table ',TABLE_NAME,';')FROMinformation_schema. TABLESWHERETABLE_SCHEMA = 'test';3.拼接kill连接SELECTconcat('KILL ', id, ';')FROMinformation_schema. PROCESSLISTWHERESTATE LIKE 'Creating sort index';4.拼接创建数据库语句SELECTCONCAT('create database ','`',SCHEMA_NAME,'`',' DEFAULT CHARACTER SET ',DEFAULT_CHARACTER_SET_NAME,';') AS CreateDatabaseQueryFROMinformation_schema.SCHEMATAWHERESCHEMA_NAME NOT IN ('information_schema','performance_schema','mysql','sys');5.拼接创建用户的语句SELECTCONCAT('create user '',user,''@'',Host,'''' IDENTIFIED BY PASSWORD '',authentication_string,'';') AS CreateUserQueryFROMmysql.`user`WHERE`User` NOT IN ('root','mysql.session','mysql.sys');#有密码字符串哦 在其他实例执行 可直接创建出与本实例相同密码的用户6.导出权限脚本 这个shell脚本也用到了拼接#!/bin/bash#Function export user privilegespwd=yourpassexpgrants(){mysql -B -u'root' -p${pwd} -N $@ -e "SELECT CONCAT('SHOW GRANTS FOR ''', user, '''@''', host, ''';' ) AS query FROM mysql.user" | mysql -u'root' -p${pwd} $@ | sed 's/(GRANT .*)/1;/;s/^(Grants for .*)/-- 1 /;/--/{x;p;x;}'}expgrants > /tmp/grants.sqlecho "flush privileges;" >> /tmp/grants.sql7.查找表碎片SELECT t.TABLE_SCHEMA,t.TABLE_NAME,t.TABLE_ROWS,concat(round(t.DATA_LENGTH / 1024 / 1024, 2), 'M') AS size,t.INDEX_LENGTH,concat(round(t.DATA_FREE / 1024 / 1024, 2), 'M') AS datafreeFROM information_schema.tables tWHERE t.TABLE_SCHEMA = 'test' order by DATA_LENGTH desc;8.查找无主键表 这个没用到拼接 也分享出来吧#查找某一个库无主键表SELECTtable_schema,table_nameFROMinformation_schema.TABLESWHEREtable_schema = 'test'AND TABLE_NAME NOT IN (SELECTtable_nameFROMinformation_schema.table_constraints tJOIN information_schema.key_column_usage k USING (constraint_name,table_schema,table_name)WHEREt.constraint_type = 'PRIMARY KEY'AND t.table_schema = 'test');#查找除系统库外 无主键表SELECTt1.table_schema,t1.table_nameFROMinformation_schema. TABLES t1LEFT OUTER JOIN information_schema.TABLE_CONSTRAINTS t2 ON t1.table_schema = t2.TABLE_SCHEMAAND t1.table_name = t2.TABLE_NAMEAND t2.CONSTRAINT_NAME IN ('PRIMARY')WHEREt2.table_name IS NULLAND t1.TABLE_SCHEMA NOT IN ('information_schema','performance_schema','mysql','sys') ;以上就是MySQL中常用的拼接语句的小结(代码示例)的详细内容,更多请关注小潘博客其它相关文章!