获取创建库的帮助
mysql> help create database; //获取帮助如何创建数据库 Name: 'CREATE DATABASE' Description: Syntax: CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name [create_specification(额外的选项)] ... create_specification: [DEFAULT] CHARACTER SET [=] charset_name | [DEFAULT] COLLATE [=] collation_name CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE privilege for the database. CREATE SCHEMA is a synonym for CREATE DATABASE. URL: http://dev.mysql.com/doc/refman/5.5/en/create-database.html
创建一个新库的过程:
mysql> CREATE DATABASE IF NOT EXISTS students CHARACTER SET 'gbk' COLLATE 'gbk_chinese_ci'; Query OK, 1 row affected (0.00 sec)
在数据目录里面会生成db.opt
文件:
[root@mysql students]# pwd /mysql/students [root@mysql students]# ls db.opt [root@mysql students]# file db.opt db.opt: ASCII text /文件类型为ascii文件 [root@mysql students]# cat db.opt default-character-set=gbk //保存内容为字符集和排序规则 default-collation=gbk_chinese_ci
修改用ALTER
命令
mysql> HELP ALTER DATABASE //使用该命令查看如何修改数据库 Name: 'ALTER DATABASE' Description: Syntax: 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> ALTER DATABASE students CHARACTER SET 'gbk' COLLATE 'gbk_bin'; Query OK, 1 row affected (0.00 sec)
获取删除库的帮助
mysql> HELP DROP DATABASE; Name: 'DROP DATABASE' Description: Syntax: DROP {DATABASE | SCHEMA} [IF EXISTS] db_name
删除:
mysql> DROP SCHEMA students; Query OK, 0 rows affected (0.00 sec) mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | fsx | | mysql | | performance_schema | | test | +--------------------+ 5 rows in set (0.00 sec)
在数据目录里面查看:
[root@mysql mysql]# ls fsx ib_logfile0 mysql mysql-bin.index mysql.pid test ibdata1 ib_logfile1 mysql-bin.000001 mysql.err performance_schema //已经没有了students数据库
数据库改名:
可以关闭服务器,在数据目录对文件重命名,即可。
或者新建数据库,数据迁移过去。一般情况不建议数据库重命名。
学习表之前,先使用该表
mysql> use students Database changed
创建表一般情况有三种方法,使用HELP
可以查看具体使用方法
mysql> HELP CREATE TABLE; //三种方式,这里的帮助信息不全,具体执行后查看 Name: 'CREATE TABLE' Description: Syntax: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,...) [table_options] [partition_options] CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)] [table_options] [partition_options] [IGNORE | REPLACE] [AS] query_expression CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name { LIKE old_tbl_name | (LIKE old_tbl_name) }
第一种:直接定义一张空表
CREATE TABLE IF NOT EXISTS table_name (col_name col_defination(最核心的是字段类型)(字段名称字段定义),constraint(约束)) ENGINE = engine_name(存储引擎) MAX_ROWS 数字(最多存储多少行)
第二种:从其它表中查询数据,并以之创建新表
第三种:仿照其他表,以之为模板,创建一个空表
关于PRIMARY KEY和UNIQUE KEY,如果是单字段,可以在定义字段信息是,后面添加。如果是多字段组合,可以最后单独定义PRIMARY KEY(),括号里面是字段名称。
**创建:**
方法一:
mysql> CREATE TABLE IF NOT EXISTS class_1(id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,name char(20) NOT NULL,age TINYINT NOT NULL);//创建表 Query OK, 0 rows affected (0.15 sec) mysql> SHOW TABLES; +--------------------+ | Tables_in_students | +--------------------+ | class_1 | +--------------------+ 1 row in set (0.00 sec) mysql> CREATE TABLE IF NOT EXISTS class_2(id INT UNSIGNED NOT NULL AUTO_INCREMENT ,name char(20) NOT NULL,age TINYINT NOT NULL,PRIMARY KEY(id));//如果主键是字段之和,就必须单独列出来 Query OK, 0 rows affected (0.15 sec) mysql> SHOW TABLES; +--------------------+ | Tables_in_students | +--------------------+ | class_1 | | class_2 | +--------------------+ 2 rows in set (0.00 sec) mysql> CREATE TABLE IF NOT EXISTS class_3(id INT UNSIGNED NOT NULL AUTO_INCREMENT ,name char(20) NOT NULL,age TINYINT NOT NULL,PRIMARY KEY(id),UNIQUE(name,age));//增加唯一键 Query OK, 0 rows affected (0.25 sec) mysql> SHOW TABLES; +--------------------+ | Tables_in_students | +--------------------+ | class_1 | | class_2 | | class_3 | +--------------------+ 3 rows in set (0.00 sec) mysql> CREATE TABLE IF NOT EXISTS class_4(id INT UNSIGNED NOT NULL AUTO_INCREMENT ,name char(20) NOT NULL,age TINYINT NOT NULL,PRIMARY KEY(id),UNIQUE(name,age),INDEX(age));//创建索引(age),索引允许值相同,索引结构都为B+Tree Query OK, 0 rows affected (0.40 sec) mysql> SHOW TABLES; +--------------------+ | Tables_in_students | +--------------------+ | class_1 | | class_2 | | class_3 | | class_4 | +--------------------+ 4 rows in set (0.00 sec) mysql> CREATE TABLE courses(cid TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,course VARCHAR(50) NOT NULL) ENGINE=MyISAM; //指定存储引擎为MyISAM Query OK, 0 rows affected (0.35 sec) mysql> show tables; +--------------------+ | Tables_in_students | +--------------------+ | class_1 | | class_2 | | class_3 | | class_4 | | courses | +--------------------+ 5 rows in set (0.00 sec) //键也称作约束,可用作索引,属于特殊索引(有特殊限定),都是B+Tree结构
查看表class_1
信息:
mysql> show table status like '%class_1' \G *************************** 1. row *************************** Name: class_1 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: 10485760 Auto_increment: 1 Create_time: 2018-05-10 18:36:26 //创建时间 Update_time: NULL //上次更新时间 Check_time: NULL Collation: gbk_chinese_ci //排序规则,继承数据库 Checksum: NULL Create_options: Comment: 1 row in set (0.00 sec) //不同的存储引擎,表信息会有不同,上面的是InnoDB,下面是MyISAM mysql> SHOW TABLE STATUS LIKE '%courses'\G *************************** 1. row *************************** Name: courses Engine: MyISAM //存储引擎为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: 2018-05-10 18:56:05 Update_time: 2018-05-10 18:56:05 Check_time: NULL Collation: gbk_chinese_ci Checksum: NULL Create_options: Comment: 1 row in set (0.00 sec)
mysql> INSERT INTO courses (course) values ('数学'),('语文'),('英语'); Query OK, 3 rows affected (0.00 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> select * from courses; +-----+--------+ | cid | course | +-----+--------+ | 1 | 数学 | | 2 | 语文 | | 3 | 英语 | +-----+--------+ 3 rows in set (0.00 sec) //注意cid是自动生成的,因为有AUTO_CREMENT函数 mysql> SHOW INDEXES FROM courses \G //显示表上的索引信息 *************************** 1. row *************************** Table: courses //表名 Non_unique: 0 //是不是非唯一键,这里是唯一键 Key_name: PRIMARY //键名称,是主键 Seq_in_index: 1 //第几个索引 Column_name: cid //创建到cid字段 Collation: A //排序规则 Cardinality: 3 Sub_part: NULL Packed: NULL Null: Index_type: BTREE //索引类型B-Tree类型 Comment: Index_comment: 1 row in set (0.00 sec)
方法二:
这里看到courses
表,就仿照它创建一个表:
mysql> CREATE TABLE testcourses SELECT * FROM courses WHERE cid <= 2; Query OK, 2 rows affected (0.16 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> SHOW TABLES; +--------------------+ | Tables_in_students | +--------------------+ | class_1 | | class_2 | | class_3 | | courses | | testcourses | +--------------------+ 5 rows in set (0.00 sec) mysql> SELECT * FROM testcourses; +-----+--------+ | cid | course | +-----+--------+ | 1 | 数学 | | 2 | 语文 | +-----+--------+ 2 rows in set (0.00 sec) mysql> DESC courses; //显示表结构 +--------+---------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+---------------------+------+-----+---------+----------------+ | cid | tinyint(3) unsigned | NO | PRI | NULL | auto_increment | | course | varchar(50) | NO | | NULL | | +--------+---------------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> DESC testcourses; +--------+---------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+---------------------+------+-----+---------+-------+ | cid | tinyint(3) unsigned | NO | | 0 | | | course | varchar(50) | NO | | NULL | | +--------+---------------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) //注意:尽管是模仿创建的表,但是很多表属性定义等会不存在了
方法三:
mysql> CREATE TABLE test LIKE courses; //第三种建立表的方式 Query OK, 0 rows affected (0.11 sec) mysql> SHOW TABLES; +--------------------+ | Tables_in_students | +--------------------+ | class_1 | | class_2 | | class_3 | | courses | | test | | testcourses | +--------------------+ 6 rows in set (0.00 sec) mysql> DESC test; +--------+---------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+---------------------+------+-----+---------+----------------+ | cid | tinyint(3) unsigned | NO | PRI | NULL | auto_increment | | course | varchar(50) | NO | | NULL | | +--------+---------------------+------+-----+---------+----------------+ 2 rows in set (0.01 sec) //这种方法建立的新表和原表属性完全一样
所谓修改表,就是对已经存在的表进行操作。加、删、改->字段、索引、表名等
修改表定义:
mysql> HELP ALTER TABLE; Name: 'ALTER TABLE' Description: Syntax: ALTER [ONLINE|OFFLINE] [IGNORE] TABLE tbl_name [alter_specification [, alter_specification] ...] [partition_options]
对test
表进行操作:
增加一个UNIQUE KEY
(唯一键):
mysql> ALTER TABLE test ADD UNIQUE KEY (course); Query OK, 0 rows affected (0.20 sec) Records: 0 Duplicates: 0 Warnings: 0 //修改字段名称 mysql> ALTER TABLE test CHANGE course Course varchar(50) NOT NULL; Query OK, 0 rows affected (0.11 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC test; +--------+---------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+---------------------+------+-----+---------+----------------+ | cid | tinyint(3) unsigned | NO | PRI | NULL | auto_increment | | Course | varchar(50) | NO | UNI | NULL | | +--------+---------------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec)
给test
表增加一个新字段
mysql> ALTER TABLE test ADD start_time date NOT NULL DEFAULT '2018-09-01'; Query OK, 0 rows affected (0.11 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC test; +------------+---------------------+------+-----+------------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+---------------------+------+-----+------------+----------------+ | cid | tinyint(3) unsigned | NO | PRI | NULL | auto_increment | | Course | varchar(50) | NO | UNI | NULL | | | start_time | date | NO | | 2018-09-01 | | +------------+---------------------+------+-----+------------+----------------+ 3 rows in set (0.00 sec) //修改字段名称练习 mysql> ALTER TABLE test CHANGE start_time end_time date NOT NULL DEFAULT '2018-07-01'; Query OK, 0 rows affected (0.42 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC test; +----------+---------------------+------+-----+------------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+---------------------+------+-----+------------+----------------+ | cid | tinyint(3) unsigned | NO | PRI | NULL | auto_increment | | Course | varchar(50) | NO | UNI | NULL | | | end_time | date | NO | | 2018-07-01 | | +----------+---------------------+------+-----+------------+----------------+ 3 rows in set (0.00 sec)
给表改名:(将test
给成test_new
)
给表重命名代价特别大,其原理是创建一个新表,将所有数据复制进去,然后删除旧表
mysql> ALTER TABLE test RENAME test_new; Query OK, 0 rows affected (0.00 sec) mysql> SHOW TABLES; +--------------------+ | Tables_in_students | +--------------------+ | class_1 | | class_2 | | class_3 | | courses | | test_new | | testcourses | +--------------------+ 6 rows in set (0.00 sec) 或者直接使用`REBANE`命令 mysql> RENAME TABLE test_new TO test;//将test_new 改成 test Query OK, 0 rows affected (0.00 sec) mysql> SHOW TABLES; +--------------------+ | Tables_in_students | +--------------------+ | class_1 | | class_2 | | class_3 | | courses | | test | | testcourses | +--------------------+ 6 rows in set (0.00 sec)
mysql> HELP DROP TABLE; Name: 'DROP TABLE' Description: Syntax: DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [, tbl_name] ... [RESTRICT | CASCADE] RESTRICT是严格模式 CASCADE是即连模式,即如果有外键连接到别的表,连带删除另外的有关系的表,CASCADE是很危险的关键字
删除class_4
:
mysql> DROP TABLE class_4; Query OK, 0 rows affected (0.52 sec)
关于外键应用:
将courses
和新创建的表classmates
使用cid
来连接起来
mysql> CREATE TABLE classmates(sid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,name VARCHAR(30),cid INT NOT NULL); //创建一个表,字段有sid,name,和cid(cid在courses表中也有可以作为外键) Query OK, 0 rows affected (0.83 sec) mysql> INSERT INTO classmates (name,cid) VALUES ('小明',2); //添加数据,直接使用cid Query OK, 1 row affected (0.16 sec) mysql> INSERT INTO classmates (name,cid) VALUES ('小红',1); Query OK, 1 row affected (0.14 sec) mysql> INSERT INTO classmates (name,cid) VALUES ('范顺心',3); Query OK, 1 row affected (0.14 sec) mysql> SELECT * FROM classmates; +-----+-----------+-----+ | sid | name | cid | +-----+-----------+-----+ | 1 | 小明 | 2 | | 2 | 小红 | 1 | | 3 | 范顺心 | 3 | +-----+-----------+-----+ 3 rows in set (0.00 sec) mysql> SELECT * FROM courses; +-----+--------+ | cid | course | +-----+--------+ | 1 | 数学 | | 2 | 语文 | | 3 | 英语 | +-----+--------+ 3 rows in set (0.00 sec) //组合查询方法: mysql> SELECT name,course FROM classmates,courses WHERE classmates.cid=courses.cid; +-----------+--------+ | name | course | +-----------+--------+ | 小明 | 语文 | | 小红 | 数学 | | 范顺心 | 英语 | +-----------+--------+ 3 rows in set (0.00 sec)
如果一个表中的cid超过了另一个表cid的范围,如:
mysql> INSERT INTO classmates (name,cid) VALUES ("小荒",5); Query OK, 1 row affected (0.14 sec) mysql> SELECT * FROM -> classmates; +-----+-----------+-----+ | sid | name | cid | +-----+-----------+-----+ | 1 | 小明 | 2 | | 2 | 小红 | 1 | | 3 | 范顺心 | 3 | | 4 | 小荒 | 5 | +-----+-----------+-----+ 4 rows in set (0.00 sec) //courses表中根本没有5cid号,如之奈何?这是需要外键约束
删除上述的例子(小荒那一行) mysql> DELETE FROM classmates WHERE cid=5; Query OK, 1 row affected (0.14 sec) mysql> SELECT * FROM classmates; +-----+-----------+-----+ | sid | name | cid | +-----+-----------+-----+ | 1 | 小明 | 2 | | 2 | 小红 | 1 | | 3 | 范顺心 | 3 | +-----+-----------+-----+ 3 rows in set (0.00 sec)
添加外键约束:
mysql> HELP CREATE TABLE; Name: 'CREATE TABLE' reference_definition: REFERENCES tbl_name (index_col_name,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] //如果另一表删了,使用什么选项 [ON UPDATE reference_option] //如果另一个表更新了,使用什么选项 reference_option: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT //使用的选项,严格模式(不允许)|连同|设置为空|无动作|默认动作 mysql> ALTER TABLE classmates ADD FOREIGN KEY (cid) REFERENCES courses(cid); ERROR 1005 (HY000): Can't create table 'students.#sql-885_4' (errno: 150) //出现了问题,因为MyISAM(courses是MyISAM)不支持事务,所以应该修改存储引擎 mysql> ALTER TABLE courses ENGINE=InnoDB; Query OK, 3 rows affected (0.24 sec) Records: 3 Duplicates: 0 Warnings: 0
外键约束:
外键约束之前要确保属性定义需要相同
mysql> ALTER TABLE classmates MODIFY cid TINYINT UNSIGNED NOT NULL; Query OK, 3 rows affected (0.57 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> DESC courses; +--------+---------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+---------------------+------+-----+---------+----------------+ | cid | tinyint(3) unsigned | NO | PRI | NULL | auto_increment | | course | varchar(50) | NO | | NULL | | +--------+---------------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> DESC classmates; +-------+---------------------+------+-----+---------+----------------+ | 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 | | +-------+---------------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) mysql> ALTER TABLE classmates ADD FOREIGN KEY foreign_cid(cid) REFERENCES courses (cid);//添加外键约束,给classmates表添加courses的约束(cid相同) Query OK, 3 rows affected (0.58 sec) Records: 3 Duplicates: 0 Warnings: 0 mysql> SHOW INDEXES FROM classmates\G *************************** 2. row *************************** Table: classmates Non_unique: 1 Key_name: foreign_cid //表明是外键约束 Seq_in_index: 1 Column_name: cid Collation: A Cardinality: 3 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: 2 rows in set (0.00 sec) mysql> INSERT INTO classmates (name,cid) VALUE ('小荒',4);//courses表中没有cid=4,则在classmates不能添加cid=4,即外键约束 ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`students`.`classmates`, CONSTRAINT `classmates_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `courses` (`cid`)) mysql> DELETE FROM courses WHERE cid=2; //同样不允删除正在被其他表引用的外键约束值 ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`students`.`classmates`, CONSTRAINT `classmates_ibfk_1` FOREIGN KEY (`cid`) REFERENCES `courses` (`cid`))
总结注意:外键和存储引擎有关系,需要InnoDB存储模式外键约束极大的消耗资源,所以不建议使用。
索引不能被修改,只能创建,删除,或者查看,索引本身是一个解构体实例化
CREATE INDEX index_name ON tb_name (字段col);
col_name length [ASC | DESC]
length指定索引长度,只索引一个字段的多少个字符值需要合理,有一定的计算法则
ASC表示升序,DESC表示降序
mysql> HELP CREATE INDEX Name: 'CREATE INDEX' Description: Syntax: CREATE [ONLINE|OFFLINE] [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name [index_type] ON tbl_name (index_col_name,...) [index_option] ... mysql> SHOW INDEXES FROM classmates; +------------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | +------------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ | classmates | 0 | PRIMARY | 1 | sid | A | 4 | NULL | NULL | | BTREE | | | | classmates | 1 | foreign_cid | 1 | cid | A | 4 | NULL | NULL | | BTREE | | | +------------+------------+-------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+ 2 rows in set (0.00 sec)
mysql> CREATE INDEX name_on_classmates ON classmates (name) USING BTREE -> ; Query OK, 0 rows affected (0.35 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> SHOW INDEXES FROM classmates \G *************************** 3. row *************************** Table: classmates Non_unique: 1 Key_name: name_on_classmates Seq_in_index: 1 Column_name: name Collation: A Cardinality: 4 Sub_part: NULL Packed: NULL Null: YES Index_type: BTREE Comment: Index_comment: 3 rows in set (0.00 sec)
删除索引使用DROP INDEX
mysql> HELP DROP INDEX; Name: 'DROP INDEX' Description: Syntax: DROP [ONLINE|OFFLINE] INDEX index_name ON tbl_name mysql> SHOW INDEXES FROM classmates \G *************************** 1. row *************************** Table: classmates Non_unique: 0 Key_name: PRIMARY Seq_in_index: 1 Column_name: sid Collation: A Cardinality: 4 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: *************************** 2. row *************************** Table: classmates Non_unique: 1 Key_name: foreign_cid Seq_in_index: 1 Column_name: cid Collation: A Cardinality: 4 Sub_part: NULL Packed: NULL Null: Index_type: BTREE Comment: Index_comment: 2 rows in set (0.00 sec)
删除索引:
mysql> DROP INDEX name_on_classmates ON classmates; Query OK, 0 rows affected (0.19 sec) Records: 0 Duplicates: 0 Warnings: 0