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      |         |               |

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

时间: 2025-01-07 04:00:12

MySQL管理表和索引的相关文章

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

SQL语句: 数据库 表 索引 视图 DML语句 单字段:    PRIMARY KEY 主键 UNIQUE KEY 唯一键 单或者多字段:    PRIMARY KEY(col,...) UNIQUE KEY(col,...) INDEX(col,...) 数据类型: data_type: BIT[(length)] 比特 | TINYINT[(length)] [UNSIGNED] [ZEROFILL] 非常小的整数(1字节) | SMALLINT[(length)] [UNSIGNED]

Mysql建表与索引使用规范详解

一. MySQL建表,字段需设置为非空,需设置字段默认值. 二. MySQL建表,字段需NULL时,需设置字段默认值,默认值不为NULL. 三. MySQL建表,如果字段等价于外键,应在该字段加索引. 四. MySQL建表,不同表之间的相同属性值的字段,列类型,类型长度,是否非空,是否默认值,需保持一致,否则无法正确使用索引进行关联对比. 五. MySQL使用时,一条SQL语句只能使用一个表的一个索引.所有的字段类型都可以索引,多列索引的属性最多15个. 六. 如果可以在多个索引中进行选择,My

随笔编号-16 MySQL查看表及索引大小方法

目标:阿里云OS数据库DMS,单个主库最大存储空间为2T.最近公司业务扩展很快,一天数据量达到7.9G左右.要求备份清理历史数据,备份到其他磁盘. 准备: 如果想知道MySQL数据库中每个表占用的空间.表记录的行数的话,可以打开MySQL的 information_schema 数据库.在该库中有一个 TABLES 表,这个表主要字段分别是: TABLE_SCHEMA : 数据库名TABLE_NAME:表名ENGINE:所使用的存储引擎TABLES_ROWS:记录数DATA_LENGTH:数据大

mysql创建表与索引

-- ---------------------------- -- 商品属性表 -- AUTO_INCREMENT=1为设置了自增长的字段设置起点,1为起点 -- ENGINE选择:MyISAM类型不支持事务处理等高级处理,而InnoDB类型支持. -- NOT NULL 设置字段不为空,DEFAULT NULL设置字段默认值 -- COMMENT注释 -- DEFAULT CHARSET=utf8为字段设置默认编码(如果表字段没有设置编码,那么默认就是这里指定的编码) -- characte

mysql 为表添加索引

索引作用 在索引列上,除了上面提到的有序查找之外,数据库利用各种各样的快速定位技术,能够大大提高查询效率.特别是当数据量非常大,查询涉及多个表时,使用索引往往能使查询速度加快成千上万倍. 例如,有3个未索引的表t1.t2.t3,分别只包含列c1.c2.c3,每个表分别含有1000行数据组成,指为1-1000的数值,查找对应值相等行的查询如下所示. SELECT c1,c2,c3 FROM t1,t2,t3 WHERE c1=c2 AND c1=c3此查询结果应该为1000行,每行包含3个相等的值

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

存储引擎 ,也被称为表类型:MyISAM表:无事务,表锁InnoDB 表:事务,行锁show enginesshow table status like '' mysql配置文件 mysqld --help --verboseDBA :开发DBA 数据库设计.SQL语句.存储过程.存储函数.触发器管理DBA 安装.升级.备份.恢复.用户管理.权限管理.监控.性能分析.基准测试数据类型 :数值型字符型日期时间型域属性,修改符每个数据类型特点:1.存入的值类型:2.占据的存储空间:3.定长还变长:4

Mysql中大表添加索引的办法

Hash索引与 Btree索引的区别http://database.51cto.com/art/201010/229525.htm Creating Indexes/Sorting on very large tables in Mysqlhttp://li.angshan.blog.163.com/blog/static/131332289201203053128110/ MySQL load data infile - acceleration?http://stackoverflow.co

MYSQL 查看表上索引的 1 方法

前期准备: create table T9(A int ,B text,C text,fulltext index fix_test_for_T8_B(B));#在定义表的时候加索引 create unique index ix_test_for_T8_A on T9(A);#加朴素索引 create fulltext index fix_test_for_T8_C on T9(C);#加全文索引 -------------------------------------------------

mysql建表建索引

建表: CREATE TABLE `sj_projects` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL DEFAULT '' COMMENT '项目名称', `platform_id` int(11) NOT NULL DEFAULT '0' COMMENT '平台id', `unique_id` varchar(255) NOT NULL DEFAULT '' COMMENT '项目和数据的唯一i