DQL 数据查询语言 IS (information_schema)

3.information_schema 统计信息库

1.介绍:

视图

1.安全: 只允许查询,不知道操作的对象是谁。
2.方便: 只需要简单的select语句即可使用。

2.作用:

1.方便我们做数据库资产统计
库/表:
个数
数据量(容量;行数)
每张表的数据字典信息

2.可以获取到server层状态信息
3.获取到InnoDB引擎层的状态信息

3.应用举例:

TABLES :

TABLE_SCHEMA:    表所在的库
TABLE_NAME:        表名
ENGINE     :        表的引擎
TABLE-ROWS:         表的行数
AVG_ROW_LENGTH:        平均行长度(字节)
INDEX_LENGTH:            索引占用长度(字节)
TABLE_COMMENT:            表注释

-- 例子:

-- 1. 简单查询体验TABLES信息
SELECT * FROM TABLES;

-- 2. 所有业务库和表的名字.
SELECT table_schema , table_name 
FROM information_schema.tables
WHERE table_schema NOT IN ('sys','information_schema','performance_schema','mysql');
-- 3. 统计每个业务库,表的个数和列表
SELECT table_schema , COUNT(table_name),GROUP_CONCAT(table_name) 
FROM information_schema.tables
WHERE table_schema NOT IN ('sys','information_schema','performance_schema','mysql')
GROUP BY table_schema;
-- 4. 统计业务数据库的总数据量
SELECT SUM(table_rows * AVG_ROW_LENGTH+index_length)/1024 AS total_KB
FROM information_schema.tables
WHERE table_schema NOT IN ('sys','information_schema','performance_schema','mysql');
-- 5. 每个业务库分别统计数据量
SELECT table_schema,SUM(table_rows * AVG_ROW_LENGTH+index_length)/1024 AS total_KB
FROM information_schema.tables
WHERE table_schema NOT IN ('sys','information_schema','performance_schema','mysql')
GROUP BY table_schema
ORDER  BY total_KB DESC ;

-- 6. top 3 数据量大的表
SELECT table_schema,table_name,(table_rows * AVG_ROW_LENGTH+index_length)/1024 AS table_kb
FROM information_schema.tables
WHERE table_schema NOT IN ('sys','information_schema','performance_schema','mysql')
ORDER BY  table_kb DESC 
LIMIT 3;


-- 7. 查询所有非INNODB的表

SELECT table_schema,table_name ,ENGINE FROM information_schema.tables
WHERE table_schema NOT IN ('sys','information_schema','performance_schema','mysql')
AND ENGINE <> 'innodb';

-- 8. 查询所有非INNODB的表 , 并且提出修改建议
SELECT 
table_schema,
table_name ,
ENGINE ,
CONCAT("alter table ",table_schema,".",table_name," engine=innodb;") AS "修改建议"
FROM information_schema.tables
WHERE table_schema NOT IN ('sys','information_schema','performance_schema','mysql')
AND ENGINE <> 'innodb';

-- 9. 所有业务库和表的名字,并且生产备份语句
SELECT 
table_schema , 
table_name ,
CONCAT("mysqldump ",table_schema," ",table_name," > /bak/",table_schema,"_",table_name,".sql") AS "备份"
FROM information_schema.tables
WHERE table_schema NOT IN ('sys','information_schema','performance_schema','mysql');

猜你喜欢

转载自www.cnblogs.com/yangxiaoni/p/12074615.html