1.2, mysql indexes and views (Linux cloud Mastering)

 

CONTEND

A, MySQL indexes

1.1 Introduction to Indexes

1.2 Classification Index

1.3 Creating an index

1.4 Management Index

Two, mysql view view

2.1 View Profile

2.2 Creating a view

View Manager 2.3 (see, modify, delete)


A, MySQL indexes

First introduced in mysql index definitions, and classification functions, and then shows you how to create an index, the index modify, view and test the index, delete the index .


1.1 Introduction to Indexes


        In MySQL index, also known as "key" can also be interpreted as a key, it is a data structure storage engine used to quickly find the record . Index for good performance is critical, especially when the amount of data in the table more and more, the index more important effect on performance.

Can be understood, the index is equivalent to the dictionary sequencer table, if you want to check a word, if you do not use the sequencer table, you will need hundreds of pages from one page to check. Index can easily improve query performance by several orders of magnitude, it is simply to improve our query data speeds.

But there are bad places, indexing will take up some resources, such as inserting data will be much slower after indexing, so we generally after the data is fully inserted in the index. Or you've built up again after the index bulk insert data it is recommended that you delete the index and then insert the data, and finally index (I say this in general in the case of massive data insertion oh, if not a lot of data, then do not pay attention to it).


1.2 Classification Index

The general index, the only index, full-text index, a separate index, multi-column index, a spatial index.

We generally establish the general index on it, the specific requirements of a particular treatment.
 

1.3 Creating an index

(1) When you create a table indexing
syntax:

CREATE TABLE 表名(
字段名1 数据类型 [完整性约束条件..],
字段名2 数据类型 [完整性约束条件..],
[UNIQUE  | FULLTEXT | SPATIAL ] INDEX | KEY
[索引名] (字段名[(长度)] [ASC | DESC])
);

Example: 

--创建普通索引示例:
CREATE TABLE department10 (
dept_id INT,
dept_name VARCHAR(30),
comment VARCHAR(50),
INDEX index_dept_name (dept_name)
);
--创建唯一索引示例:
CREATE TABLE department11 (
dept_id INT,
dept_name VARCHAR(30),
comment VARCHAR(50),
UNIQUE INDEX index_dept_name (dept_name)
);
--创建全文索引示例:
CREATE TABLE department12 (
dept_id INT,
dept_name VARCHAR(30),
comment VARCHAR(50),
log text, 
FULLTEXT INDEX index_log (log)
);

 

After indexing (2) create table

grammar:

CREATE [UNIQUE | FULLTEXT | SPATIAL ] INDEX 索引名
        ON 表名 |  (字段名[(长度)] [ ASC | DESC ]);


Example:

--1、创建普通索引示例:
CREATE INDEX index_dept_name ON department (dept_name);

--2、创建唯一索引示例:
CREATE UNIQUE INDEX index_dept_name ON department (dept_name);

--3、创建全文索引示例:
CREATE FULLTEXT INDEX index_dept_name ON department (dept_name);

--4、创建多列索引示例:
CREATE INDEX index_dept_name_comment ON department (dept_name,comment);

 Alter also be used to modify the index, but create enough, I will not alter slightly less.

1.4 Management Index

View index:

show create table 表名\G

Test Example:

explain select * from department where dept_name='HR';

Delete the index:

show create table employee; --首先查看创建表的结构,知道了索引名才可以删除哦

drop index 索引名 on 表名;

Let's do a little test to understand the difference before and after the creation of the index query:

use company   #进入company数据库
create table t1(id int name ,varchar(50));  #创建一个t1表
delimiter $$   --定义分隔符方便后面创建存储过程
#下面这就是创建存储过程,实现批量插入数据,这个后面我会写博客介绍的,在这里就是实现批量插入数据的功能
create procedure autoinsert() 
begin 
declare i int default 1;
while(i<200000)do  
 insert into company.t1 values(i,'ggg');   
 set i=i+1; 
end while; 
end$$

delimiter ;   #把分隔符修改回来
call autoinsert(); #执行这个函数,开始插入数据
desc t1;  --先查看下表的结构,现在是没有索引的
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int         | YES  |     | NULL    |       |
| name  | varchar(50) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+

select * from t1 where id =100000;  --注意观察查询时间,0.11s
+--------+------+
| id     | name |
+--------+------+
| 100000 | ggg  |
+--------+------+
1 row in set (0.11 sec)

--用explain查看测试下,竟然查了200242行!没有使用index
explain select * from t1 where id =190000\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t1
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 200242
     filtered: 10.00
        Extra: Using where

--开始建立索引进行比对
create index index_id on t1(id);
desc t1;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int         | YES  | MUL | NULL    |       |
| name  | varchar(50) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
--查询时间为0!
select * from t1 where id =100000;
+--------+------+
| id     | name |
+--------+------+
| 100000 | ggg  |
+--------+------+
1 row in set (0.00 sec)

--再测试下,它使用了我们建立的索引查询,仅用了一行就查到了
explain select * from t1 where id =190000\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t1
   partitions: NULL
         type: ref
possible_keys: index_id
          key: index_id
      key_len: 5
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.00 sec)

 

Two, mysql view view

2.1 View Profile

MySQL view is a virtual table, the contents of which is defined by the query. With real tables, view contains a series of columns and rows of data with a name. However, in view there is no set of data values stored in the database . Data consisting of rows and columns to define the table referenced by the query view, and dynamically generated when the reference view. The underlying tables cited therein, the role of MySQL view similar to screening. Screening may be defined from the current view or a plurality of other databases or tables, or other views. Query through a view without any restrictions, and few restrictions when data is modified by them.
         View is a SQL query stored in the database, it is mainly for two reasons: For security reasons, the view can hide some data, such as: some sensitive information, the other reason is that you can make complex queries easy to understand and use.
 

2.2 Creating a view

语法一:
CREATE [ALGORITHM = {UNDEFINED |MERGE | TEMPTABLE} ]
VIEW 视图名[(字段1,字段2..)]
AS SELECT语句
[WITH [ CASCADED | LOCAL ] CHECK OPTION ];

语法二:
CREATE VIEW 视图名 AS SELECT语句;

(1) Generally, we choose the second grammar it is relatively simple. To see a single table to create a view following example:

create view mysql_user 
    -> as select user,host,authentication_string from mysql.user;

select * from mysql_user;   --就可以直接查看视图,不用敲那么长的语句了
+------------------+-----------+------------------------------------------------------------------------+
| user             | host      | authentication_string                                                  |
+------------------+-----------+------------------------------------------------------------------------+
| mysql.infoschema | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| mysql.session    | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| mysql.sys        | localhost | $A$005$THISISACOMBINATIONOFINVALIDSALTANDPASSWORDTHATMUSTNEVERBRBEUSED |
| root             | localhost | $A$005$M	1#_\Jr5v(ji?qEIdRVMpdu8z0CQEQ2m9OAyJh5Z.uSnn2sJW4xnzTiis0 |
+------------------+-----------+-----------------------------------------------------------

(2) create a multi-table view case

Let's create two tables and insert data, and then create the view.

create table product( id int unsigned auto_increment primary key, name varchar(30) ) not null, price double not null);

create table sale( id int unsigned auto_increment primary key, name varchar(30) not null, quantity int not null default 0, get_time datetime not null);

insert into product(name,price) values ('apple',10), ('banana',2.5), ('peach',4);  
insert into sale(name,quantity,get_time) values
    -> ('apple',100,now()),
    -> ('banana',150,now()),
    -> ('peach',200,now());

First with a select statement to query the total price, but each time the query is very troublesome, it is easy to create a query view. 

select product.id,product.name,price*quantity as 'total_price' from sale,product where product.name=sale.name;
+----+--------+-------------+
| id | name   | total_price |
+----+--------+-------------+
|  1 | apple  |        1000 |
|  2 | banana |         375 |
|  3 | peach  |         800 |
+----+--------+-------------+

--创建视图
create view total_price as select product.id,product.name,price*quantity as 'total_price' from sale,product where product.name=sale.name;

select * from total_price;
+----+--------+-------------+
| id | name   | total_price |
+----+--------+-------------+
|  1 | apple  |        1000 |
|  2 | banana |         375 |
|  3 | peach  |         800 |
+----+--------+-------------+

If the two tables insert data, the view will change: 

insert into product(name,price) values ('orange',5);

insert into sale(name,quantity,get_time) values ('orange',120,now());

select * from total_price;
+----+--------+-------------+
| id | name   | total_price |
+----+--------+-------------+
|  1 | apple  |        1000 |
|  2 | banana |         375 |
|  3 | peach  |         800 |
|  4 | orange |         600 |
+----+--------+-------------+

View Manager 2.3 (see, modify, delete)

(1) View View

1.SHOW TABLES;  --查看视图名

2.SHOW TABLE STATUS;
--示例:查看数据库mysq|中视图及所有表详细信息
SHOW TABLE STATUS FROM mysql\G

--示例:查看数据库shop中视图名total_price的详细信息
SHOW TABLE STATUS FROM shop LIKE 'total_price'\G

3.SHOW CREATE VIEW
--示例:查看视图定义信息
SHOW CREATE VIEW total_price\G

4.DESCRIBE
--示例:查看视图结构
DESC total_price;

(2) modify the view

--方法一:删除后新创建
DROP VIEW view_user;
CREATE VIEW view_user AS SELECT user,host FROM mysql.user;
SELECT * FROM view_user;

--方法二: ALTER修改视图
ALTER VIEW 视图名 AS SELECT语句; 
ALTER VIEW view_user AS SELECT user,password FROM mysql.user;

(3) Delete View

--语法
DROP VIEW view_name [,view_name]..;
--示例
USE mysql;
DROP VIEW view_user;


 

 

 

 

 

 

 

 

 

 

Published 28 original articles · won praise 51 · views 10000 +

Guess you like

Origin blog.csdn.net/Until_U/article/details/105381905