当前位置:网站首页>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
边栏推荐
- Final review of information and network security (full version)
- How does wechat prevent withdrawal come true?
- Flink源码解读(二):JobGraph源码解读
- February database ranking: how long can Oracle remain the first?
- Jetpack compose 1.1 release, based on kotlin's Android UI Toolkit
- Install docker under windows10 (through Oracle VM VirtualBox)
- Resume of a microservice architecture teacher with 10 years of work experience
- Garbage first of JVM garbage collector
- JVM垃圾回收概述
- 在 vi 编辑器中的命令模式下,删除当前光标处的字符使用 __ 命 令。
猜你喜欢
MySQL字符串函数
EasyRE WriteUp
Programmer orientation problem solving methodology
Activiti directory (IV) inquiry agency / done, approved
Resume of a microservice architecture teacher with 10 years of work experience
一个数10年工作经验的微服务架构老师的简历
JVM之垃圾回收器下篇
Final review of information and network security (based on the key points given by the teacher)
C# WinForm中DataGridView单元格显示图片
[reverse primary] Unique
随机推荐
【MMdetection】一文解决安装问题
Logical operation instruction
唯有学C不负众望 TOP1环境配置
Interpretation of Flink source code (III): Interpretation of executiongraph source code
【逆向初级】独树一帜
Instructions for Redux
轻量级计划服务工具研发与实践
唯有学C不负众望 TOP4 S1E6:数据类型
Shawshank's sense of redemption
07个人研发的产品及推广-人力资源信息管理系统
PostgreSQL 14.2, 13.6, 12.10, 11.15 and 10.20 releases
Activiti directory (IV) inquiry agency / done, approved
SQL tuning notes
À propos de l'utilisation intelligente du flux et de la carte
JVM之垃圾回收器下篇
【逆向】脱壳后修复IAT并关闭ASLR
After idea installs the plug-in, restart the plug-in and disappear
Flink源码解读(一):StreamGraph源码解读
Control transfer instruction
案例:检查空字段【注解+反射+自定义异常】