MySQL管理表和索引

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL管理表和索引相关的知识,希望对你有一定的参考价值。

创建数据库: 

mysql> HELP CREATE DATABASE;  查看创建数据库的帮助信息

CREATE DATABASE|SCHEMA   [IF NOT EXISTS](在数据库不存在的时候才创建 ) db_name [CHARACTER SET=](指定字符集)   [COLLATE=](指定排序规则)

mysql> show character set; 显示所有的字符集 

mysql> show collation; 查看排序规则



mysql> CREATE SCHEMA IF NOT EXISTS students CHARACTER SET ‘gbk‘ COLLATE ‘gbk_chinese_ci‘;

[[email protected] ~]# ls /mydata/data/students

db.opt

[[email protected] ~]# cat /mydata/data/students/db.opt 

default-character-set=gbk

default-collation=gbk_chinese_ci

   


修改数据库:

mysql> help alter database;



    ALTER {DATABASE | SCHEMA} [db_name]

    alter_specification ...

ALTER {DATABASE | SCHEMA} db_name

    UPGRADE DATA DIRECTORY NAME


alter_specification:

    [DEFAULT] CHARACTER SET [=] charset_name

  | [DEFAULT] COLLATE [=] collation_name




删除数据库:

mysql> help  drop database;


DROP {DATABASE | SCHEMA} [IF EXISTS] db_name


  


创建表:

mysql> help create table;

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name  直接定义一张空表

    (create_definition,...)

    [table_options]

    [partition_options]


Or:


CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name   或者从其他表中查询出数据,并以之创建新表

    [(create_definition,...)]

    [table_options]

    [partition_options]

    select_statement


Or:


CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name    仿造其他表创建一个空表

    { LIKE old_tbl_name | (LIKE old_tbl_name) }



table_option:

    ENGINE [=] engine_name  指定表的存储引擎

  | AUTO_INCREMENT [=] value  自动增长从哪个值开始

  | AVG_ROW_LENGTH [=] value  平均长度

  | [DEFAULT] CHARACTER SET [=] charset_name 字符集

  | CHECKSUM [=] {0 | 1}  是否启用校验和

  | [DEFAULT] COLLATE [=] collation_name 排序规则

  | COMMENT [=] ‘string‘  注释

  | CONNECTION [=] ‘connect_string‘ 

  | DATA DIRECTORY [=] ‘absolute path to directory‘数据目录

  | DELAY_KEY_WRITE [=] {0 | 1}

  | INDEX DIRECTORY [=] ‘absolute path to directory‘索引目录

  | INSERT_METHOD [=] { NO | FIRST | LAST }

  | KEY_BLOCK_SIZE [=] value

  | MAX_ROWS [=] value 最多允许存储多少行

  | MIN_ROWS [=] value

  | PACK_KEYS [=] {0 | 1 | DEFAULT}

  | PASSWORD [=] ‘string‘

  | ROW_FORMAT [=] {DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT} 行格式

  | TABLESPACE tablespace_name [STORAGE {DISK|MEMORY|DEFAULT}] 表空间

  | UNION [=] (tbl_name[,tbl_name]...)


create tables [if not exists] tb_name (cool_name col_defination,constraint)


create table tb1 (ID int unsigned not null  auto_increment primary key,NAME char(20) not null,AGE tinyint not null);

create table tb2 (ID int unsigned not null  auto_increment ,NAME char(20) not null,AGE tinyint not null,primary key(ID),unique key(NAME),index(AGE));


mysql> create table courses(CID tinyint unsigned not null auto_increment primary key, COUSE varchar(50) not null);


mysql> show table status like ‘courses‘\G 查看表的存储引擎

*************************** 1. row ***************************

           Name: courses

         Engine: InnoDB

        Version: 10

     Row_format: Compact

           Rows: 0

 Avg_row_length: 0

    Data_length: 16384

Max_data_length: 0

   Index_length: 0

      Data_free: 0

 Auto_increment: 1

    Create_time: 2016-10-01 19:48:43

    Update_time: NULL

     Check_time: NULL

      Collation: gbk_chinese_ci

       Checksum: NULL

 Create_options: 

        Comment: 

1 row in set (0.00 sec)


mysql> drop table courses;指定存储引擎 

mysql> create table courses(CID tinyint unsigned not null auto_increment primary key, COUSE varchar(50) not null) engine=myisam;

mysql> show table status like ‘courses‘\G

*************************** 1. row ***************************

           Name: courses

         Engine: MyISAM

        Version: 10

     Row_format: Dynamic

           Rows: 0

 Avg_row_length: 0

    Data_length: 0

Max_data_length: 281474976710655

   Index_length: 1024

      Data_free: 0

 Auto_increment: 1

    Create_time: 2016-10-01 19:53:36

    Update_time: 2016-10-01 19:53:36

     Check_time: NULL

      Collation: gbk_chinese_ci

       Checksum: NULL

 Create_options: 

        Comment: 

1 row in set (0.00 sec)


往表里插入数据

mysql> insert into courses (COUSE) values (‘yuwen‘),(‘shuxue‘),(‘wuli‘);

mysql> insert into courses (COUSE) values (‘yuwen‘),(‘shuxue‘),(‘wuli‘);


mysql> select * from courses; 查看

+-----+--------+

| CID | COUSE  |

+-----+--------+

|   1 | yuwen  |

|   2 | shuxue |

|   3 | wuli   |

|   4 | yuwen  |

|   5 | shuxue |

|   6 | wuli   |

+-----+--------+

6 rows in set (0.00 sec)


mysql> show indexes from courses; 查看表上的索引

+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| Table   | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |

+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| courses |          0 | PRIMARY  |            1 | CID         | A         |           6 |     NULL | NULL   |      | BTREE      |         |               |

+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

1 row in set (0.00 sec)


mysql> create table courses2 select * from courses where CID <=2; 以courses中的数据来创建一个新表

mysql> select * from courses2;

+-----+--------+

| CID | COUSE  |

+-----+--------+

|   1 | yuwen  |

|   2 | shuxue |

+-----+--------+

2 rows in set (0.00 sec)




mysql> desc  courses2; 查看表结构

+-------+---------------------+------+-----+---------+-------+

| Field | Type                | Null | Key | Default | Extra |

+-------+---------------------+------+-----+---------+-------+

| CID   | tinyint(3) unsigned | NO   |     | 0       |       |

| COUSE | varchar(50)         | NO   |     | NULL    |       |

+-------+---------------------+------+-----+---------+-------+

2 rows in set (0.01 sec)


mysql> desc courses;

+-------+---------------------+------+-----+---------+----------------+

| Field | Type                | Null | Key | Default | Extra          |

+-------+---------------------+------+-----+---------+----------------+

| CID   | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |

| COUSE | varchar(50)         | NO   |     | NULL    |                |

+-------+---------------------+------+-----+---------+----------------+

2 rows in set (0.00 sec)


mysql> create table test like courses;以现有的表结构创建一个空表

mysql> desc test;

+-------+---------------------+------+-----+---------+----------------+

| Field | Type                | Null | Key | Default | Extra          |

+-------+---------------------+------+-----+---------+----------------+

| CID   | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |

| COUSE | varchar(50)         | NO   |     | NULL    |                |

+-------+---------------------+------+-----+---------+----------------+


单字段

   primary key

   unique  key

单或多字段

   pramary key (col,...)

   unique  key (col,...)

   index (col,...)





修改表:

mysql> help alter table;

ALTER [ONLINE | OFFLINE] [IGNORE] TABLE tbl_name

    [alter_specification [, alter_specification] ...]

    [partition_options]



mysql> desc test;

+-------+---------------------+------+-----+---------+----------------+

| Field | Type                | Null | Key | Default | Extra          |

+-------+---------------------+------+-----+---------+----------------+

| CID   | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |

| COUSE | varchar(50)         | NO   |     | NULL    |                |

+-------+---------------------+------+-----+---------+----------------+

2 rows in set (0.00 sec)


mysql> show indexes from test;

+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |

+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| test  |          0 | PRIMARY  |            1 | CID         | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |

+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

1 row in set (0.00 sec)






往test表添加一个唯一键索引

mysql> alter table test add unique key (COUSE); 

mysql> show indexes from test;

+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |

+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| test  |          0 | PRIMARY  |            1 | CID         | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |

| test  |          0 | COUSE    |            1 | COUSE       | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |

+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+





修改一个字段的名称:

mysql> alter table test change COUSE COURSE varchar(50) not null;


mysql> desc test;

+--------+---------------------+------+-----+---------+----------------+

| Field  | Type                | Null | Key | Default | Extra          |

+--------+---------------------+------+-----+---------+----------------+

| CID    | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |

| COURSE | varchar(50)         | NO   | UNI | NULL    |                |

+--------+---------------------+------+-----+---------+----------------+





新增一个字段:

mysql> alter table test add STARTTIME date default ‘2016-10-02‘;

mysql> desc test;

+-----------+---------------------+------+-----+------------+----------------+

| Field     | Type                | Null | Key | Default    | Extra          |

+-----------+---------------------+------+-----+------------+----------------+

| CID       | tinyint(3) unsigned | NO   | PRI | NULL       | auto_increment |

| COURSE    | varchar(50)         | NO   | UNI | NULL       |                |

| STARTTIME | date                | YES  |     | 2016-10-02 |                |

+-----------+---------------------+------+-----+------------+----------------+



给表重命名:

mysql> alter table test rename to COURSES10;

mysql> show tables ;

+--------------------+

| Tables_in_students |

+--------------------+

| COURSES10          |

| courses            |

| courses2           |

+--------------------+


或者:

mysql> rename table COURSES10 to test;

mysql> show tables ;

+--------------------+

| Tables_in_students |

+--------------------+

| courses            |

| courses2           |

| test               |

+--------------------+





删除表:

mysql> help drop table;

DROP [TEMPORARY] TABLE [IF EXISTS]

    tbl_name [, tbl_name] ...

    [RESTRICT | CASCADE]



mysql> create table  student (SID int unsigned not null auto_increment primary key,NAME varchar(30),CID int not null);

mysql> insert into student (NAME,CID) value (‘zhangsan‘,‘1‘),(‘lisi‘,‘2‘),(‘wangwu‘,‘3‘);

mysql> select * from student;

+-----+----------+-----+

| SID | NAME     | CID |

+-----+----------+-----+

|   1 | zhangsan |   1 |

|   2 | lisi     |   2 |

|   3 | wangwu   |   3 |

+-----+----------+-----+

mysql> select * from courses;

+-----+--------+

| CID | COUSE  |

+-----+--------+

|   1 | yuwen  |

|   2 | shuxue |

|   3 | wuli   |

|   4 | yuwen  |

|   5 | shuxue |

|   6 | wuli   |

+-----+--------+


使用组合查询:

mysql> select NAME,COUSE from student,courses where student.CID=courses.CID;

+----------+--------+

| NAME     | COUSE  |

+----------+--------+

| zhangsan | yuwen  |

| lisi     | shuxue |

| wangwu   | wuli   |

+----------+--------+




删除表的字段:

mysql> delete from student where NAME=‘wangwu‘;


修改表引擎:

mysql> alter table courses engine=innodb;













引用型约束:(innodb才支持外键)

mysql> alter table student  modify CID tinyint unsigned not null;

mysql> desc student;

+-------+---------------------+------+-----+---------+----------------+

| Field | Type                | Null | Key | Default | Extra          |

+-------+---------------------+------+-----+---------+----------------+

| SID   | int(10) unsigned    | NO   | PRI | NULL    | auto_increment |

| NAME  | varchar(30)         | YES  |     | NULL    |                |

| CID   | tinyint(3) unsigned | NO   |     | NULL    |                |

+-------+---------------------+------+-----+---------+----------------+


mysql> desc courses;

+-------+---------------------+------+-----+---------+----------------+

| Field | Type                | Null | Key | Default | Extra          |

+-------+---------------------+------+-----+---------+----------------+

| CID   | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |

| COUSE | varchar(50)         | NO   |     | NULL    |                |

+-------+---------------------+------+-----+---------+----------------+

mysql> alter table student add foreign key (CID) references courses(CID); 创建一个外键约束

mysql> show indexes from student;

+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| Table   | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |

+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| student |          0 | PRIMARY  |            1 | SID         | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |

| student |          1 | CID      |            1 | CID         | A         |           2 |     NULL | NULL   |      | BTREE      |         |               |

+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+


mysql> select * from courses;

+-----+--------+

| CID | COUSE  |

+-----+--------+

|   1 | yuwen  |

|   2 | shuxue |

|   3 | wuli   |

|   4 | yuwen  |

|   5 | shuxue |

|   6 | wuli   |

+-----+--------+

mysql> insert into student (NAME,CID) value (‘maliu‘,‘7‘);

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`students`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`CID`) REFERENCES `courses` (`CID`))


mysql> delete from courses where CID=‘3‘;

ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`students`.`student`, CONSTRAINT `student_ibfk_1` FOREIGN KEY (`CID`) REFERENCES `courses` (`CID`))






创建索引:

mysql> show indexes from student;

+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| Table   | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |

+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| student |          0 | PRIMARY  |            1 | SID         | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |

| student |          1 | CID      |            1 | CID         | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |

+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+


mysql> create index NAME_ON_STUDENT on student (NAME) using btree;

mysql> show indexes from student;

+---------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| Table   | Non_unique | Key_name        | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |

+---------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| student |          0 | PRIMARY         |            1 | SID         | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |

| student |          1 | CID             |            1 | CID         | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |

| student |          1 | NAME_ON_STUDENT |            1 | NAME        | A         |           3 |     NULL | NULL   | YES  | BTREE      |         |               |

+---------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+


索引创建:

create index INDEX_NAME on TB_NAME (col,...);

mysql> help create index;

CREATE [ONLINE|OFFLINE] [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name

    [index_type]

    ON tbl_name (index_col_name,...)

    [index_option] ...

index_col_name:

    col_name [(length)] [ASC | DESC]             #length从最左侧开始进行比较     ASC升序,DESC降序


index_type:

    USING {BTREE | HASH}


index_option:

    KEY_BLOCK_SIZE [=] value

  | index_type

  | WITH PARSER parser_name

  | COMMENT ‘string‘




删除索引:

mysql> help drop index;

DROP [ONLINE|OFFLINE] INDEX index_name ON tbl_name

mysql> drop index NAME_ON_STUDENT on student;


mysql> create index NAME_ON_STUDENT on student (NAME(5) desc) using btree; 


mysql> show indexes from student;

+---------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| Table   | Non_unique | Key_name        | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |

+---------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+

| student |          0 | PRIMARY         |            1 | SID         | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |

| student |          1 | CID             |            1 | CID         | A         |           3 |     NULL | NULL   |      | BTREE      |         |               |

| student |          1 | NAME_ON_STUDENT |            1 | NAME        | A         |           3 |        5 | NULL   | YES  | BTREE      |         |               |

+---------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+









本文出自 “运维成长路” 博客,谢绝转载!

以上是关于MySQL管理表和索引的主要内容,如果未能解决你的问题,请参考以下文章

MySQL管理表和索引

Linux命令:MySQL系列之四--MySQL管理表和索引

Mysql数据库理论基础之四 --- 表和索引的管理

MYSQl之数据类型及sql模型管理表和索引

mysql 分区

mysql 分区