【MySQL】經常使用拼接語句

**前言:**在MySQL中 CONCAT ()函數用於將多個字符串鏈接成一個字符串,利用此函數咱們能夠將原來一步沒法獲得的sql拼接出來,在工做中也許會方便不少,下面主要介紹下幾個經常使用的場景。mysql

*注:*適用於5.7版本 低版本可能稍許不一樣。sql

1.拼接查詢全部用戶
SELECT DISTINCT
	CONCAT(
		'User: \'',
		USER,
		'\'@\'',
		HOST,
		'\';'
	) AS QUERY
FROM
	mysql.USER;
# 當拼接字符串中出現'時 需使用\轉義符
複製代碼
2.拼接DROP table
SELECT
	CONCAT(
		'DROP table ',
		TABLE_NAME,
		';'
	)
FROM
	information_schema. TABLES
WHERE
	TABLE_SCHEMA = 'test';
複製代碼
3.拼接kill鏈接
SELECT
	concat('KILL ', id, ';')
FROM
	information_schema. PROCESSLIST
WHERE
	STATE LIKE 'Creating sort index';
複製代碼
4.拼接建立數據庫語句
SELECT
	CONCAT(
		'create database ',
		'`',
    SCHEMA_NAME,
    '`',
    ' DEFAULT CHARACTER SET ',
    DEFAULT_CHARACTER_SET_NAME,
		';'
	) AS CreateDatabaseQuery
FROM
	information_schema.SCHEMATA
WHERE
	SCHEMA_NAME NOT IN (
		'information_schema',
		'performance_schema',
		'mysql',
		'sys'
	);
複製代碼
5.拼接建立用戶的語句
SELECT
	CONCAT(
		'create user \'',
    user,
    '\'@\'',
    Host,
    '\''
    ' IDENTIFIED BY PASSWORD \'',
    authentication_string,
		'\';'
	) AS CreateUserQuery
FROM
	mysql.`user`
WHERE
	`User` NOT IN (
		'root',
		'mysql.session',
		'mysql.sys'
	);
#有密碼字符串哦 在其餘實例執行 可直接建立出與本實例相同密碼的用戶
複製代碼
6.導出權限腳本 這個shell腳本也用到了拼接
#!/bin/bash 
#Function export user privileges 

pwd=yourpass  
expgrants()  
{  
  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.sql
echo "flush privileges;" >> /tmp/grants.sql
複製代碼
7.查找表碎片
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 datafree
FROM information_schema.tables t
WHERE t.TABLE_SCHEMA = 'test' order by DATA_LENGTH desc;
複製代碼
8.查找無主鍵表 這個沒用到拼接 也分享出來吧
#查找某一個庫無主鍵表
SELECT
table_schema,
table_name
FROM
    information_schema.TABLES
WHERE
    table_schema = 'test'
AND TABLE_NAME NOT IN (
    SELECT
        table_name
    FROM
        information_schema.table_constraints t
    JOIN information_schema.key_column_usage k USING (
        constraint_name,
        table_schema,
        table_name
    )
    WHERE
        t.constraint_type = 'PRIMARY KEY'
    AND t.table_schema = 'test'
);

#查找除系統庫外 無主鍵表
SELECT
	t1.table_schema,
	t1.table_name
FROM
	information_schema. TABLES t1
LEFT OUTER JOIN information_schema.TABLE_CONSTRAINTS t2 ON t1.table_schema = t2.TABLE_SCHEMA
AND t1.table_name = t2.TABLE_NAME
AND t2.CONSTRAINT_NAME IN ('PRIMARY')
WHERE
	t2.table_name IS NULL
AND t1.TABLE_SCHEMA NOT IN (
	'information_schema',
	'performance_schema',
	'mysql',
	'sys'
) ;
複製代碼

歡迎你們收藏,其餘同窗有沒有相似實用的語句呢 也能夠分享出來哦!shell

相關文章
相關標籤/搜索