CREATE TABLE table_name [col_name data_type]
[UNIQUE | FULLTEXT | SPATIAL] [INDEX | KEY] [index_name] (col_name [length]) [ASC |
DESC]
参数 | 说明 |
---|---|
UNIQUE | FULLTEXT | SPATIAL | 可选参数,分别表示唯一索引、全文索引和空间索引 |
INDEX | KEY | 同义词,两者的作用相同,用来指定创建索引 |
index_name | 指定索引的名称,为可选参数,如果不指定,那么MySQL默认col_name为索引名 |
col_name | 为需要创建索引的字段列,该列必须从数据表中定义的多个列中选择 |
length | 为可选参数,表示索引的长度,只有字符串类型的字段才能指定索引长度 |
ASC | DESC | 指定升序或者降序的索引值存储 |
CREATE TABLE book(
book_id INT ,
book_name VARCHAR(100),
authors VARCHAR(100),
info VARCHAR(100) ,
comment VARCHAR(100),
year_publication YEAR,
INDEX(year_publication)
);
CREATE TABLE test1(
id INT NOT NULL,
name varchar(30) NOT NULL,
UNIQUE INDEX uk_idx_id(id)
);
CREATE TABLE student (
id INT(10) UNSIGNED AUTO_INCREMENT ,
student_no VARCHAR(200),
student_name VARCHAR(200),
PRIMARY KEY(id)
);
CREATE TABLE test2(
id INT NOT NULL,
name CHAR(50) NULL,
INDEX single_idx_name(name(20))
);
CREATE TABLE test3(
id INT(11) NOT NULL,
name CHAR(30) NOT NULL,
age INT(11) NOT NULL,
info VARCHAR(255),
INDEX multi_idx(id,name,age)
);
CREATE TABLE test4(
id INT NOT NULL,
name CHAR(30) NOT NULL,
age INT NOT NULL,
info VARCHAR(255),
FULLTEXT INDEX futxt_idx_info(info)
);
CREATE TABLE articles (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR (200),
body TEXT,
FULLTEXT index (title, body)
);
CREATE TABLE `papers` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(200) DEFAULT NULL,
`content` text,
PRIMARY KEY (`id`),
FULLTEXT KEY `title` (`title`,`content`)
);
# 不同于like方式的的查询
SELECT * FROM papers WHERE content LIKE ‘%查询字符串%’;
# 全文索引用 match + against 方式查询
SELECT * FROM papers WHERE MATCH(title,content) AGAINST (‘查询字符串’);
空间索引创建中,要求空间类型的字段必须为
非空
。
CREATE TABLE test5(
geo GEOMETRY NOT NULL,
SPATIAL INDEX spa_idx_geo(geo)
) ENGINE=MyISAM;
ALTER TABLE
语句创建索引ALTER TABLE table_name ADD [UNIQUE | FULLTEXT | SPATIAL] [INDEX | KEY]
[index_name] (col_name[length],...) [ASC | DESC]
CREATE INDEX
创建索引CREATE [UNIQUE | FULLTEXT | SPATIAL] INDEX index_name
ON table_name (col_name[length],...) [ASC | DESC]
SHOW INDEX FROM
mysql> SHOW INDEX FROM student\G
*************************** 1. row ***************************
Table: student
Non_unique: 0
Key_name: PRIMARY
Seq_in_index: 1
Column_name: id
Collation: A
Cardinality: 3611769
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
Visible: YES
Expression: NULL
*************************** 2. row ***************************
Table: student
Non_unique: 1
Key_name: name
Seq_in_index: 1
Column_name: name
Collation: A
Cardinality: 773608
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
Index_comment:
Visible: YES
Expression: NULL
2 rows in set (0.00 sec)
mysql>
SHOW CREATE TABLE
mysql> SHOW CREATE TABLE `student`;
+---------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| student | CREATE TABLE `student` (
`id` int NOT NULL AUTO_INCREMENT,
`stuno` int NOT NULL,
`name` varchar(20) DEFAULT NULL,
`age` int DEFAULT NULL,
`classId` int DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=4000001 DEFAULT CHARSET=utf8mb3 |
+---------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
mysql>
DESC
mysql> DESC `student`;
+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| stuno | int | NO | | NULL | |
| name | varchar(20) | YES | MUL | NULL | |
| age | int | YES | | NULL | |
| classId | int | YES | | NULL | |
+---------+-------------+------+-----+---------+----------------+
5 rows in set (0.02 sec)
mysql>
删除表中的列时,如果要删除的列为索引的组成部分,则该列也会从索引中删除;如果组成索引的所有列都被删除,则整个索引将被删除。
ALTER TABLE
删除索引ALTER TABLE table_name DROP INDEX index_name;
DROP INDEX
语句删除索引DROP INDEX index_name ON table_name;
隐藏索引(invisible indexes)
,只需要将待删除的索引设置为隐藏索引,使查询优化器不再使用这个索引(即使使用force index(强制使用索引),优化器也不会使用该索引)。这种通过先将索引设置为隐藏索引,再删除索引的方式就是软删除
。# 比普通索引多了一个关键字 INVISIBLE,用来标记索引为不可见索引。
CREATE TABLE tablename(
propname1 type1[CONSTRAINT1],
propname2 type2[CONSTRAINT2],
……
propnamen typen,
INDEX [indexname](propname1 [(length)]) INVISIBLE
);
CREATE INDEX indexname
ON tablename(propname[(length)]) INVISIBLE;
ALTER TABLE tablename
ADD INDEX indexname (propname [(length)]) INVISIBLE;
ALTER TABLE tablename ALTER INDEX index_name INVISIBLE; #切换成隐藏索引
ALTER TABLE tablename ALTER INDEX index_name VISIBLE; #切换成非隐藏索引
use_invisible_indexes
)来打开某个设置,使隐藏索引对查询优化器可见。off(默认)
,优化器会忽略隐藏索引。mysql> select @@optimizer_switch \G
*************************** 1. row ***************************
@@optimizer_switch: index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on,index_condition_pushdown=on,mrr=on,mrr_cost_based=on,block_nested_loop=on,batched_key_access=off,materialization=on,semijoin=on,loosescan=on,firstmatch=on,duplicateweedout=on,subquery_materialization_cost_based=on,use_index_extensions=on,condition_fanout_filter=on,derived_merge=on,use_invisible_indexes=off,skip_scan=on,hash_join=on,subquery_to_derived=off,prefer_ordering_index=on,hypergraph_optimizer=off,derived_condition_pushdown=on
1 row in set (0.00 sec)
mysql> set session optimizer_switch="use_invisible_indexes=on";
Query OK, 0 rows affected (0.00 sec)
mysql> select @@optimizer_switch \G
*************************** 1. row ***************************
@@optimizer_switch: ... use_invisible_indexes=on, ...
1 row in set (0.00 sec)
mysql> set session optimizer_switch="use_invisible_indexes=off";
Query OK, 0 rows affected (0.00 sec)
mysql>
CREATE DATABASE atguigudb1;
USE atguigudb1;
#1.创建学生表和课程表
CREATE TABLE `student_info` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`student_id` INT NOT NULL ,
`name` VARCHAR(20) DEFAULT NULL,
`course_id` INT NOT NULL ,
`class_id` INT(11) DEFAULT NULL,
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `course` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`course_id` INT NOT NULL ,
`course_name` VARCHAR(40) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
# 函数1:创建随机产生字符串函数
DELIMITER //
CREATE FUNCTION rand_string(n INT)
RETURNS VARCHAR(255) #该函数会返回一个字符串
BEGIN
DECLARE chars_str VARCHAR(100) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ';
DECLARE return_str VARCHAR(255) DEFAULT '';
DECLARE i INT DEFAULT 0;
WHILE i < n DO
SET return_str = CONCAT(return_str, SUBSTRING(chars_str, FLOOR(1 + RAND() * 52), 1));
SET i = i + 1;
END WHILE;
RETURN return_str;
END //
DELIMITER ;
#函数2:创建随机数函数
DELIMITER //
CREATE FUNCTION rand_num (from_num INT ,to_num INT) RETURNS INT(11)
BEGIN
DECLARE i INT DEFAULT 0;
SET i = FLOOR(from_num + RAND() * (to_num - from_num + 1)) ;
RETURN i;
END //
DELIMITER ;
假如报错:
This function has none of DETERMINISTIC ......
,解释一下原因:
mysql> show variables like 'log_bin';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_bin | ON |
+---------------+-------+
1 row in set (0.01 sec)
mysql>
允许创建函数
:set global log_bin_trust_function_creators=1;
# 存储过程1:创建插入课程表存储过程
DELIMITER //
CREATE PROCEDURE insert_course( max_num INT )
BEGIN
DECLARE i INT DEFAULT 0;
SET autocommit = 0; #设置手动提交事务
REPEAT #循环
SET i = i + 1; #赋值
INSERT INTO course (course_id, course_name ) VALUES (rand_num(10000,10100), rand_string(6));
UNTIL i = max_num
END REPEAT;
COMMIT; #提交事务
END //
DELIMITER ;
# 存储过程2:创建插入学生信息表存储过程
DELIMITER //
CREATE PROCEDURE insert_stu( max_num INT )
BEGIN
DECLARE i INT DEFAULT 0;
SET autocommit = 0; #设置手动提交事务
REPEAT #循环
SET i = i + 1; #赋值
INSERT INTO student_info (course_id, class_id ,student_id ,NAME )
VALUES (rand_num(10000,10100),rand_num(10000,10200),rand_num(1,200000),rand_string(6));
UNTIL i = max_num
END REPEAT;
COMMIT; #提交事务
END //
DELIMITER ;
CALL insert_course(100);
CALL insert_stu(1000000);
对分组或者排序的字段进行索引
。递增的顺序
进行展示,所以在去重的时候也会快很多。连接表的数量尽量不要超过 3 张
,因为每增加一张表就相当于增加了一次嵌套的循环,数量级增长会非常快,严重影响查询的效率。对 WHERE 条件创建索引
,因为 WHERE 才是对数据条件的过滤。如果在数据量非常大的情况下,没有 WHERE 条件过滤是非常可怕的。对用于连接的字段创建索引
,并且该字段在多张表中的类型必须一致
。比如 course_id 在 student_info 表和 course 表中都为 int(11) 类型,而不能一个为 int 另一个为 varchar 类型。mysql> SELECT s.course_id, s.name, s.student_id, c.course_name
-> FROM student_info s JOIN course c
-> ON s.course_id = c.course_id
-> WHERE s.name = 'KtMHZa';
+-----------+--------+------------+-------------+
| course_id | name | student_id | course_name |
+-----------+--------+------------+-------------+
| 10070 | KtMHZa | 6660 | erwjFx |
+-----------+--------+------------+-------------+
1 row in set (0.29 sec)
mysql> ALTER TABLE `student_info` ADD INDEX(name);
Query OK, 0 rows affected (5.73 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SELECT s.course_id, s.name, s.student_id, c.course_name
-> FROM student_info s JOIN course c
-> ON s.course_id = c.course_id
-> WHERE s.name = 'KtMHZa';
+-----------+--------+------------+-------------+
| course_id | name | student_id | course_name |
+-----------+--------+------------+-------------+
| 10070 | KtMHZa | 6660 | erwjFx |
+-----------+--------+------------+-------------+
1 row in set (0.00 sec)
mysql>
count(distinct left(列名, 索引长度)) / count(*)
计算区分度来决定截取的长度,一般区分度达到 90% 即合格。select
count(distinct left(address,10)) / count(*) as sub10, -- 截取前10个字符的选择度
count(distinct left(address,15)) / count(*) as sub11, -- 截取前15个字符的选择度
count(distinct left(address,20)) / count(*) as sub12, -- 截取前20个字符的选择度
count(distinct left(address,25)) / count(*) as sub13 -- 截取前25个字符的选择度
from shop;
数据量小
的表最好不要使用索引;大量重复
(高于10%)数据的列上不要建立索引;经常更新
的表创建过多的索引;无序的值
作为索引,例如身份证、UUID(在索引比较时需要转为ASCII,并且插入时可能造成页分裂)、MD5、HASH、无序长字符串等;# 通过 idx_name_birthday_phone_number 索引就可以对 name 列进行快速搜索,再创建一
# 个专门针对 name 列的索引就算是一个 冗余索引 ,维护这个索引只会增加维护的成本,并不会对搜索有
# 什么好处。
CREATE TABLE person_info(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
birthday DATE NOT NULL,
phone_number CHAR(11) NOT NULL,
country varchar(100) NOT NULL,
PRIMARY KEY (id),
KEY idx_name_birthday_phone_number (name(10), birthday, phone_number),
KEY idx_name (name(10))
);
# col1 既是主键、又给它定义为一个唯一索引,还给它定义了一个普通索引,可是主键本身就
# 会生成聚簇索引,所以定义的唯一索引和普通索引是重复的
CREATE TABLE repeat_index_demo (
col1 INT PRIMARY KEY,
col2 INT,
UNIQUE uk_idx_c1 (col1),
INDEX idx_c1 (col1)
);