当前位置:网站首页>MySQL index and view
MySQL index and view
2022-06-12 14:40:00 【Once_ day】
Mysql Index and view of
author:onceday date:2022 year 6 month 5 Japan
1. Index Overview
It is a structure that sorts the values of a single column or multiple columns in a database . Application index , Can greatly improve the speed of query .
The advantage of indexing is that you don't have to traverse the entire database , But the disadvantage is that maintaining the index requires physical space , And elapsed time .
The index will affect the insert operation of the database , When inserting data into an indexed table , The database system sorts by index .
The index generally includes B Trees (Btree) Index and hash (Hash) Indexes .
Indexes fall into the following categories :
- General index : Indexes that do not apply any restrictions , The index can be created in any data type , The constraints of the field itself can determine whether its value is empty or unique . Users can query by index .
- Uniqueness index : Use UNIQUE Parameter can set a unique index . When you create an index , Its value is unique , Users can quickly locate a record , A primary key is a special unique index .
- Full-text index : Use FULLTEXT Parameter can be set to full text index . Full text index can only be created in CHAR、VARCHAR perhaps TEXT Type field on . When querying string type fields with large amount of data , Using full-text index can improve query speed . By default , Apply full-text search case insensitive . If the column of the index uses binary sorting , Execute case sensitive full-text indexing .
- Single index : A single column index only corresponds to the index of one field , Can include common indexes , Uniqueness index , Full text index, etc . You need to ensure that the index value corresponds to a field .
- Multi column index : Create an index on multiple fields of the table , The index points to the corresponding fields at the time of creation , Users can query through these fields . The user must use the first of these fields to apply the index .
- Spatial index : Use SPATIAL Parameter can be set as spatial index , Spatial indexes can only be built on spatial data types , This can improve the efficiency of the system to obtain spatial data .
2. Create indexes when creating data tables
The basic syntax for creating an index when creating a data table is as follows :
create table table_name(
Property name data type [ constraint condition ],
Property name data type [ constraint condition ]
......
Property name data type
[UNIQUE | FULLTEXT | SPATIAL] INDEX|KEY
[ Alias ]( Property name 1 [( length )][ASC|DESC])
);
among , The attribute value after the attribute name , The meaning is as follows :
unique: optional , Indicates that the index is unique .fulltext: optional , Indicates that the index is full-text search .spatial: optional , Indicates that the index is a space .
index and key Parameter is used to specify the field index , Just choose one of them .
Alias as an option , Its function is to give the created index a new name .
- Property name 1: Refers to the field name corresponding to the index , The field must be pre-defined .
- length : optional , Refers to the length of the index , Must be a string type to use .
- ASC/DESC: optional ,ASC Indicates ascending order ,DESC The parameter indicates the descending order .
2.1 General index
No need to add unique,fulltext And so on .
create table score(
id int(11) auto_increment primary key not null,
name varchar(50) not null,
math int(5) not null,
english int(5) not null,
chinese int(5) not null,
index(id));
mysql> desc score;
+---------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | | NULL | |
| math | int | NO | | NULL | |
| english | int | NO | | NULL | |
| chinese | int | NO | | NULL | |
+---------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
2.2 Create a unique index
Need to use unique Parameters to constrain .
create table address(
id int(11) auto_increment primary key not null,
name varchar(50),
address varchar(200),
unique index address(id asc));
mysql> show create table address;
| address | CREATE TABLE `address` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`address` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `address` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 |
1 row in set (0.01 sec)
A unique index can constrain the uniqueness of a field , But it can not improve the search speed of users .
2.3 Create full text index
The creation of full-text index can only be used in char、varchar、text Type field on . Creating a full-text index requires fulltext Parameters to constrain .
create table cards(
id int(11) auto_increment primary key not null,
name varchar(50),
number bigint(11),
info varchar(50),
fulltext key cards_info(info)) engine=MyISAM;
Be careful : Only MyISAM Type of data table supports fulltext Full-text index ,InnoDB Or other types of data tables do not support full-text indexing .
2.4 Create a single column index
Create a single column index , That is to create an index on a single field in the data table . Creating this type of index does not require the introduction of constraint parameters , Users only need to specify a single column field name when creating .
create table telephone(
id int(11) primary key auto_increment not null,
name varchar(50) not null,
tel varchar(50) not null,
index tel_num(tel(20)));
2.5 Create multi column indexes
Specify multiple fields of the table to achieve .
create table information(
id int(11) auto_increment primary key not null,
name varchar(50) not null,
sex varchar(5) not null,
birthday varchar(50) not null,
index info(name,sex));
In a multi column index , Only the first of these fields is used in the query criteria , Indexes are used . If you don't use the first field , Then the index doesn't work , Users want to optimize query speed , This kind of index form can be applied .
2.6 Create spatial index
Need to set up SPATIAL Parameters , Only MyISAM The type table supports this type index . Index fields must have non null constraints .
create table list(
id int(11) primary key auto_increment not null,
goods geometry not null,
spatial index listinfo(goods))engine=MyISAM;
The data type corresponding to the spatial index must be the spatial data type .
3. Create an index in an established data table
It can be in the table that has been created , Create an index on one or more fields that already exist .
create [unique | fulltext | spatial] index_name
on table_name( attribute [(length)][asc | desc]);
Parameter description :
- index_name For index name , Give the user created index a new name .
- table_name Is the name of the watch , Specify the name of the table to create the index .
- Optional parameters , Specify the index type , Include
unique( unique index )、fulltext( Full-text index )、spatial( Spatial index ). - Property parameters , Specify the field name corresponding to the index . This field must already be pre stored in the data table that the user wants to operate , If the field specified by the user does not exist in the data table , The system will prompt an exception .
- length Is an optional parameter , Used to specify the index length .
- asc and desc Parameters , Specify the sort order of the data table .
3.1 Create a normal index
create index stu_info on studentinfo(sid);
3.2 Create unique index
create unique index Index name on Data table name ( Field name );
create unique index index1_id on index1(cid);
3.3 Create full text index
create fulltext index Index name on Data table name ( Field name )
create fulltext index index2_info on index2(info);
3.4 Create a single column index
create index Index name on Data table name ( Field name ( length ));
create index index3_addr on index3(address(4));
3.5 Create multi column indexes
create index Index name on Data table name ( Field name 1, Field name 2,......);
create index index4_na on index4(name,address);
It is the same as creating a multi column index when creating a data table , When creating a multi column index , The user must use the first field as the query criteria , Otherwise, the index cannot take effect .
3.6 Create spatial index
create spatial index Index name on Data table name ( Field );
among ,spatial Used to set the index as a spatial index , The data table type to be operated by the user must be MyISAM type , And the field name must have a non empty constraint , Otherwise, the spatial index cannot be created normally .
4. Modify data table structure to add index
Modify the index that already exists on the table , Can pass ALTER TABLE Statement add index to data table , Its basic structure is as follows :
alter table table_name add [unique | fulltext | spatial] index index_name( Property name [(length)] [asc|desc]);
4.1 Add a normal index
alter table studentinfo add index timer (time(20));
4.2 Add unique index
alter table Table name add unique index The index name *( Field name );
4.3 Add full text index
Full text index creation can only work on char,varchar,text Type field on .
alter table Table name add fulltext index The index name ( Field name );
alter table workinfo add fulltext index index_ext(address);
4.4 Add a single column index
Creating a single column index is the same when creating a data table , You can set a single column index .
alter table Table name add index The index name ( Field name ( length ));
4.5 Add multi column index
Use ALTER Modifying the data table structure can also add multi column indexes .
alter table Table name add index The index name ( Field name 1, Field name 2,......);
4.6 Add spatial index
alter table Table name add spatial index The index name ( Field name );
The data table type is required myIASAM type , Its field name must also have a non empty constraint .
5. Delete index
After index creation , If the user no longer needs the index , You can delete the index of the specified table .
drop index index_name on table_name;
Parameters index_name Is the index name that the user needs to delete , Parameters table_name Specify the name of the data table .
drop index index_id on workinfo;
6. Create view
6.1 Concept
The view is a virtual table , Is a table exported from one or more tables in a database , Its content is defined by query . Like a real watch , The view contains a series of named columns and rows of data .
Only the definition of view is stored in the database , There is no data in the view .
When using views to query data , The database system will take the corresponding data from the original table .
6.2 The function of view
A view works like a filter .
- simplicity : What you see is what you need , Simplified operation , There is no need to specify all the conditions for each operation .
- Security : View security prevents unauthorized users from viewing specific rows and columns , The method to enable authorized users to see only specific rows in the table is as follows :
- Add a column to the table to mark the user name
- Create view , So that users can only see the line marked with their user name .
- Authorize the view to other users .
- Logical data independence : Views can make the application and database tables independent to a certain extent . Programs can be built on top of views , So the program and database tables are separated by views .
6.3 View the permission to create a view
need create view Authority , At the same time, it should have the name of the column involved in the query SELECT jurisdiction .
select Selete_priv,Create_view_priv from mysql.user where user=" user name ";
Select_priv: Property indicates whether the user hasselectjurisdiction ,Y To haveselectjurisdiction ,N It means that there is no .Create_view_priv: Property indicates whether the user hascreate viewjurisdiction ,mysql.userExpress mysql Database user surface .- “ user name ” Parameter indicates whether you want to query whether you have
dropPrivileged user , This parameter needs to be enclosed in single quotation marks .
select Select_priv,Create_view_priv from mysql.user where user="root";
6.4 Steps to create a view
create [algorithm = {undefined|merge|temptable}]
view View name [( Attribute list )]
as select sentence
[with [cascaded]local] check option];
- algorithm, Algorithm for view selection
- “ View name ” Parameters , Represents the name of the view to be created .
- “ Attribute list “, Specifies the noun for each attribute in the view , By default, it is the same as
selectThe properties of the query in the statement are the same . - select The statement parameter is a complete query statement , Indicates to find the records that meet the conditions from a table , Import these records into the view .
- with check option Is an optional parameter , It means that when updating a view, it must be within the permission range of the view .
Create a view in a data table :
create view
book_view1(a_sort,a_talk,a_books)
as select sort,talk,books
from tb_book
Create views in multiple data tables :
create algorithm=merge view
book_view1(a_sort,a_talk,a_books,a_name)
as select sort,talk,books,tb_user.name from tb_book,tb_name where tb_book.id=tb_name.id with local check option;
matters needing attention :
- Running the statement to create a view requires the user to have the ability to create a view (create view) Authority , If you add [or replace] when , You also need to have the ability to delete the view (drop view) Authority .
selectStatement cannot contain from Subquery in Clause .selectStatements cannot reference system or user variables .selectStatement cannot reference preprocessing statement parameters .- In a stored subroutine , Definitions cannot refer to subroutine parameters or local variables .
- The table or view referenced in the definition must exist , But after creating the view , Tables or views that define references can be discarded , It can be done by
check tableCheck the view definition for such problems 、 - Cannot reference... In the definition temporary surface , Can't create temporary View .
- The table named in the view definition must already exist .
- You cannot associate a trigger with a view .
- Allowed in view definition order by, If the selected view has its own order by sentence , The... In the view definition will be ignored order by.
6.5 View view
The first way :
describe View name ;
The second way :
desc View name ;
The third way :
show table status like ' View name ';
- "like" Indicates that the string is matched later ;
- “ View name ” Parameter refers to the name of the view to be viewed , Need to define with single quotation marks .
show table status like 'book_view1';
The fourth way :
show create view View name
show create view book_view1;
6.6 Modify the view
The first way , You can modify a view when it exists , Create views when they don't exist .
create or replace [algorithm = {undefined|merge|temptable}]
view View [( Attribute list )]
as select sentence
[with [cascaded|local]check option];
The second way :
alter view [algorithm={merge | temptable|undefined}]
view view_name [(column_list)]
as select_statement[with [cascaded | local] check option]
- view_name: View name
- select——statement:SQL Statement is used to qualify the view .
When creating a view , In the use of the with check option,with encryption,with schemabing ,view_metadata After these functions , If you want to preserve the functionality provided by these options , Must be in alter view Include them in the statement .
6.7 Update the view
Updating a view is actually updating a table , Update view is to insert... Through view (insert)、 to update (update) And delete (delete) Table data .
When updating through a view , Must be converted to the basic table to update , And you can only update the data within your permission , Out of range , You can't update .
update book_view2 set a_book="php Typical table " where id=27;
It is best not to update data through views , Easy to fail , Many restrictions :
- The view contains count()、sum()、max()、min() Such as function .
- The view contains union、union all、distinct、group by、havig Other key words .
- Constant view
- In the view select Contains subqueries .
- Views exported from non updatable views .
- When creating a view ,algorithm by temptable type .
- There are columns without default values in the table corresponding to the view , And the column is not included in the view .
6.8 Delete view
To delete a view is to delete a view that already exists in the database . When deleting a view , You can only delete the definition of a view , Capture delete data .
have access to drop view To delete the view , The user must have drop jurisdiction .
drop view if exists < View name > [restrict | cascade]
- IF EXISTS Parameters are used to determine whether a view exists , If it exists, execute , If it does not exist, it will not execute .
- “ View name ” The list parameter indicates the name and list of the view to be deleted , The view names are separated by commas .
notes : This content is collected on the Internet , For the purpose of study and communication only !
边栏推荐
- Introduction to functions (inline functions and function overloading)
- Raspberry pie get temperature and send pictures to email
- JMeter (V) pressure test of Excel file upload interface
- The difference between parameter and argument in C language
- ADSL
- [ROC] aspriseocr C # English, Digital identification (not Chinese)
- QT realize picture dragging
- The original Xiaoyuan personal blog project that has been around for a month is open source (the blog has basic functions, including background management)
- Copy word content to excel and automatically divide it into multiple columns
- 掌门教育被强制退市:上市仅一年时间 软银CMC损失惨重
猜你喜欢

Socket model of punctual atom stm32f429 core board

我愿称之为史上最全的深度学习面经总结(附答案详解)

QT multi thread drawing and real-time refreshing method

Configuring OSPF pseudo connection for Huawei devices

完美收官|详解 Go 分布式链路追踪实现原理

Location (I) error: command erred out with exit status

新技术:高效的自监督视觉预训练,局部遮挡再也不用担心!

Detailed explanation of factory pattern (simple factory pattern, factory method pattern, abstract factory pattern) Scala code demonstration

【OCR】AspriseOCR C# 英文、數字識別(中文不行)

你敢信?开发一个管理系统我只用了两天
随机推荐
Player practice 19 xaudio turn on audio
[datetmeformatter] realize the conversion between localdatetime and text
Player actual combat 16 xdecode class
【OCR】AspriseOCR C# 英文、數字識別(中文不行)
jenkins的RPC测试项目
Player actual combat 22 to solve the problems of flower screen and Caton
Use Baidu AIP to obtain the text in the specified area of the screen
完美收官|详解 Go 分布式链路追踪实现原理
Player actual combat 12 QT playing audio
Raspberry pie get temperature and send pictures to email
JD scanning code to obtain cookies
【Instant】1. Equivalent to date class 2 Represents a moment
Conversion of player's actual 10 pixel format and size
Player practice 26 adding slider and window maximization
Appnium (I) basic use of appnium
你敢信?開發一個管理系統我只用了兩天
Three common methods of C language array initialization ({0}, memset, for loop assignment) and their principles
对某热水软件的加密参数逆向
[MySQL] basic database operation
Unit test (I) unit test with JUnit