在需要备份数据库里面的数据时,我们需要知道数据库占用了多少磁盘大小,可以通过一些sql语句查询到整个数据库的容量,也可以单独查看表所占容量。

  1、要查询表所占的容量,就是把表的数据和索引加起来就可以了

select sum(DATA_LENGTH)+sum(INDEX_LENGTH) from information_schema.tables 
where table_schema='数据库名';

  上面获取的结果是以字节为单位的,可以通过除两个1024的到M为单位的结果。

  2、查询所有的数据大小

select concat(round(sum(DATA_LENGTH/1024/1024),2),'M') as data_size from information_schema.tables; -- 查询所有的数据大小

  3、查询某个表的数据

select concat(round(sum(DATA_LENGTH/1024/1024),2),'M') from information_schema.tables where table_schema=’数据库名’ AND table_name=’表名’;

 

在mysql中有一个information_schema数据库,这个数据库中装的是mysql的元数据,包括数据库信息、数据库中表的信息等。所以要想查询数据库占用磁盘的空间大小可以通

  过对information_schema数据库进行操作。

information_schema中的表主要有:

  schemata表:这个表里面主要是存储在mysql中的所有的数据库的信息

  tables表:这个表里存储了所有数据库中的表的信息,包括每个表有多少个列等信息。

  columns表:这个表存储了所有表中的表字段信息。

  statistics表:存储了表中索引的信息。

  user_privileges表:存储了用户的权限信息。

  schema_privileges表:存储了数据库权限。

  table_privileges表:存储了表的权限。

  column_privileges表:存储了列的权限信息。

  character_sets表:存储了mysql可以用的字符集的信息。

  collations表:提供各个字符集的对照信息。

  collation_character_set_applicability表:相当于collations表和character_sets表的前两个字段的一个对比,记录了字符集之间的对照信息。

  table_constraints表:这个表主要是用于记录表的描述存在约束的表和约束类型。

  key_column_usage表:记录具有约束的列。

  routines表:记录了存储过程和函数的信息,不包含自定义的过程或函数信息。

  views表:记录了视图信息,需要有show view权限。

  triggers表:存储了触发器的信息,需要有super权限。

 

其他参考 :

1. 查看该数据库实例下所有库大小,,包括数据大小、索引大小,得到的结果是以MB为单位

mysql> select table_schema, sum(data_length)/1024/1024 as data_length,sum(index_length)/1024/1024 as index_length,sum(data_length+index_length)/1024/1024 as sum from information_schema.tables;
注:这里的 table_schema 会导致执行报错,table_schema 列值不止一个

2、查看该实例下各个库大小,包括数据大小、索引大小

mysql> select table_schema, sum(data_length+index_length)/1024/1024 as total_mb, sum(data_length)/1024/1024 as data_mb, sum(index_length)/1024/1024 as index_mb, count(*) as tables, curdate() as today from information_schema.tables group by table_schema order by 2 desc;

3、查看单个库的大小,包括数据大小、索引大小

mysql> select concat(truncate(sum(data_length)/1024/1024,2),'mb') as data_size, concat(truncate(sum(max_data_length)/1024/1024,2),'mb') as max_data_size, concat(truncate(sum(data_free)/1024/1024,2),'mb') as data_free, concat(truncate(sum(index_length)/1024/1024,2),'mb') as index_size from information_schema.tables where table_schema = 'db_goods';

4、查看单个表的状态

mysql> show table status from db_goods where name = 'tbl_goods' \G

5、查看单库下所有表的状态

mysql> select table_name, (data_length/1024/1024) as data_mb , (index_length/1024/1024) as index_mb, ((data_length+index_length)/1024/1024) as all_mb, table_rows from information_schema.tables where table_schema = 'db_goods';
会展示该库下的各个表的表名、数据大小、索引大小、行数。

select * from information_schema.tables where table_schema = 'db_goods';
查询数据库'db_goods'的各个表的创建信息,包括表类型、引擎类型、行数、数据长度、索引长度、字符集类型、注释;等等。