当前位置:网站首页>MySQL advanced (index, view, stored procedure, function, password modification)
MySQL advanced (index, view, stored procedure, function, password modification)
2022-07-06 17:25:00 【Tang Monk riding white horse】
Indexes
mysql The index of is like the table of contents page of a dictionary ( Indexes ) equally , We can press Pinyin 、 stroke 、 A catalogue sorted by radicals, etc ( Indexes ) Quickly find the words you need .
Indexes are divided into single column indexes and composite indexes . Single index , That is, an index contains only a single column , A table can have multiple single-column indexes , But this is not a composite index . Composite index , That is, an index contains multiple columns .
When you create an index , You need to make sure that the index is applied to SQL Conditions of query statement ( As a general WHERE Condition of clause ). actually , Index is also a table , The table holds the primary key and index fields , And points to the record of the entity table .
Although indexing can speed up data retrieval , But using index too much will lead to abuse . So index also has its disadvantages : Although the index greatly improves the query speed , At the same time, it will reduce the speed of updating the table , Such as on the table INSERT、UPDATE and DELETE. Because when updating tables ,MySQL Not only to save data , And save the index file . Index files that take up disk space .
General index
- Look at the index
show index from Table name ;
- Create index
Mode one : Create index when creating table
CREATE TABLE create_index(
id INT PRIMARY KEY,
NAME VARCHAR(10) UNIQUE,
age INT,
INDEX age_index(age)
);
Mode two : For existing tables , Add index
// If the specified field is a string , You need to specify the length , The recommended length is the same as the length when defining the field
// If the field type is not a string , You can leave out the length section
create index The index name on Table name ( Field name ( length ))
example :
create index age_index on create_index(age);
create index name_index on create_index(name(10));
- Delete index
drop index The index name on Table name ;
- Turn on Runtime Monitoring
set profiling=1;
- Check the execution time
show profiles;
- Modify table structure ( Add index )
ALTER table tableName ADD INDEX indexName(columnName)
ALTER TABLE create_index ADD INDEX name_index(NAME(10))
unique index
Similar to the previous normal index , The difference is that : The value of the index column must be unique , But you can have an empty value . If it's a composite index , The combination of column values must be unique . There are several ways to create it :
- Create unique index
CREATE UNIQUE INDEX indexName ON mytable(username(length))
CREATE UNIQUE INDEX name_index2 ON create_index(name(10))
- Modify the table structure to create a unique index
ALTER table mytable ADD UNIQUE [indexName] (username(length));
ALTER TABLE create_index ADD UNIQUE name_index3(name(10));
- When creating a table, specify
CREATE TABLE create_index(
ID INT NOT NULL,
name VARCHAR(16) NOT NULL,
UNIQUE [indexName] (username(length))
);
- Use ALTER Command add index
// There are four ways to add indexes to a data table :
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list): This statement adds a primary key , This means that the index value must be unique , And cannot be NULL.
ALTER TABLE tbl_name ADD UNIQUE index_name (column_list): The value of the index created by this statement must be unique ( except NULL Outside ,NULL There may be many times ).
ALTER TABLE tbl_name ADD INDEX index_name (column_list): Add a normal index , Index values can appear multiple times .
ALTER TABLE tbl_name ADD FULLTEXT index_name (column_list): The statement specifies that the index is FULLTEXT , For full-text indexing .
View
For complex queries , Used in many places , If demand changes , You need to change sql sentence , It needs to be modified in multiple places , It's very troublesome to maintain .
solve : Define views
The essence of view is the encapsulation of query , Define views , It is suggested that v_ start
grammar :
create view View name as select sentence ;
- example : Create view , Query students' corresponding score information
create view v_stu_score_course as
select
stu.*,cs.courseNo,cs.name courseName,sc.score
from
students stu
inner join scores sc on stu.studentNo = sc.studentNo
inner join courses cs on cs.courseNo = sc.courseNo
CREATE VIEW v_stu AS
SELECT
name,sex
FROM
students
// Use view
SELECT * FROM v_stu
- View view : The view table will list all the views as well
show tables;
- Delete view
drop view View name ;
example :
drop view v_stu_score_course;
- Use view : The purpose of a view is to query
select * from v_stu_score_course;
SELECT * FROM v_stu
stored procedure
stored procedure (Stored Procedure) It's a complex program stored in a database , A database object that can be called by an external program . Stored procedures are designed to accomplish specific functions SQL Statements set , Compiled, created and stored in a database , The user can specify the name of the stored procedure and give the parameters ( When needed ) To call execution . Stored procedures are very simple in mind , Database SQL Language level code encapsulation and reuse .
advantage
- Stored procedures can be encapsulated , And hide complex business logic .
- Stored procedures can return values , And can accept parameters .
- Stored procedures cannot be used SELECT Command to run , Because it's a subroutine , And view table , Data tables or user-defined functions are different .
- Stored procedures can be used for data validation , Enforce business logic, etc .
shortcoming
- stored procedure , Often customized to a specific database , Because the supported programming languages are different . When switching to the database system of other manufacturers , You need to rewrite the original stored procedure .
- Performance tuning and writing of stored procedures , Limited by various database systems .
- grammar :
delimiter $$
create procedure Stored procedure name ( parameter list )
begin
sql sentence
end$$
delimiter ;
- explain : delimiter Used to set the separator , The default is semicolon
- analysis : By default , Stored procedures are associated with the default database , If you want to specify that the stored procedure is created under a specific database , Then prefix the procedure name with the database name . When defining a process , Use DELIMITER
$$
The command changes the closing symbol of a statement from a semicolon ; Temporarily changed to two $$, So that the semicolon used in the process body is passed directly to the server , Not by the client ( Such as mysql) explain . - Example :
requirement : Create query process , Search for student information - step1: Set the separator
delimiter $$
- step2: Create stored procedure
create procedure proc_stu()
begin
select * from students;
end$$
- step3: Restore delimiter
delimiter ;
- Call syntax :
call stored procedure ( parameter list );
Calling stored procedure proc_stu
call proc_stu();
function
- Create function syntax
delimiter $$
create function The name of the function ( parameter list ) returns Return type
begin
sql sentence
end
$$
delimiter ;
- Example of function
requirement : Create a function my_trim, Used to delete the spaces on the left and right sides of the string - step1: Set the separator
delimiter $$
- step2: Create a function
create function my_trim(str varchar(100)) returns varchar(100)
begin
return ltrim(rtrim(str));
end
$$
- step3: Restore delimiter
delimiter ;
- Use custom functions
select ' abc ',my_trim(' abc ')
- summary :
- Stored procedures and functions are designed to operate the database repeatedly sql Collection of statements .
- Stored procedures and functions are compiled at one time , It will be cached , The next time you use it, you will directly hit the compiled... In the cache sql, There is no need to compile repeatedly
- Reduce network interaction , Reduce network access traffic
Change Password
explain : modify user The password of the table is the password of modifying the database
- Use root Sign in , modify mysql Database user surface
- Use password() Function for password encryption
- Note that the permissions need to be refreshed after modification
use mysql;
update user set password=password(' New password ') where user=' user name ';
example :
update user set password=password('123') where user='root';
Refresh the permissions : flush privileges;
forget root Account password
1、 To configure mysql You don't need a password to log in , Modify the configuration file
- Centos in : The configuration file location is /data/server/mysql/my.cnf
- Windows in : The configuration file location is C:\Program Files (x86)\MySQL\MySQL Server 5.1\my.ini modify , find mysqld, On the next line , add to skip-grant-tables
[mysqld]
skip-grant-tables
2、 restart mysql, Password free login , modify mysql Database user surface
use mysql;
update user set password=password(' New password ') where user=' user name ';
example :
update user set password=password('123') where user='root';
Refresh the permissions : flush privileges;
3、 Restore profile , Just add the skip-grant-tables Delete , restart
边栏推荐
猜你喜欢
1. Introduction to JVM
Wu Jun's trilogy insight (V) refusing fake workers
Garbage first of JVM garbage collector
JVM garbage collector part 2
TCP's three handshakes and four waves
Set up the flutter environment pit collection
JVM之垃圾回收器上篇
1. JVM入门介绍
Idea resolving jar package conflicts
JVM class loading subsystem
随机推荐
Flink 解析(三):内存管理
Redis quick start
Shawshank's sense of redemption
灵活报表v1.0(简单版)
Jetpack compose 1.1 release, based on kotlin's Android UI Toolkit
À propos de l'utilisation intelligente du flux et de la carte
Flink源码解读(二):JobGraph源码解读
ByteDance overseas technical team won the championship again: HD video coding has won the first place in 17 items
On the clever use of stream and map
1. JVM入门介绍
DOS function call
MySQL optimization notes
[VNCTF 2022]ezmath wp
肖申克的救赎有感
Wu Jun's trilogy experience (VII) the essence of Commerce
CentOS7上Redis安装
Activit fragmented deadly pit
vscode
EasyRE WriteUp
Activit零零碎碎要人命的坑