当前位置:网站首页>MySQL statement
MySQL statement
2022-06-12 16:41:00 【My guest, do you want to eat or stay】
database
show databases; // View all databases
select database(); // View the current database
create database [if not exists] Database name [default charset Character set ] [collate Sort rule ]; // Create database
show create database Database name ; // view the database
drop database [if exists] Database name ; // Delete database
use Database name ; // Using a database
alter database Database name character set Character set ; // Database character set modification
surface
show tables; // Query all tables in the current database
show create table Table name ; // View table's MySQL command
create table Table name ( Field 1 Field type , Field 2 Field type ... Field n Field type ); // Create table
desc Table name ; // View table structure
alter table Table name add Field name type ; // Add table fields
alter table Table name modify Field name New data types ; // Modify the table field type
alter table Table name change Old field name new field name type ; // Modify the field name and field type
alter table Table name drop Field name ; // Delete table fields
alter table Table name rename to The new name of the table ; // Modify the name of the table
drop table [if exists] Table name ; // Delete table
truncate table Table name ; // Delete and rebuild table
Data control language
use mysql; select * from user; // Query the user
create user ' user name '@' Host name ' identified by ' password '; // Create user
alter user ' user name '@' Host name ' identified with mysql_native_password by ' New password '; // Change Password
drop user ' user name '@' Host name ' // Delete user
show grants for ' user name '@' Host name '; // Query authority
grant Permission list on Database name to ' user name '@' Host name '; // Grant authority
revoke Permission list on Database name . Table name from ' user name '@' Host name '; // Revoke authority
CRUD
select Field 1, Field 2, Field 3 ... from Table name // Query field
select Field 1 [as Alias 1], Field 2 [as Alias 2] ... from Table name ; // set a table name
select distinct Field list from Table name ; // duplicate removal
select Field list from Table name where Field in( value 1, value 2...); //in Inquire about
select Field list from Table name where Field between value 1 and value 2; //between...and...
select Field list from Table name where Field is not null; // Null value query
select Field list from Table name where Conditions and Conditions ; //and Inquire about
select Field list from Table name where Conditions or Conditions ; //or Inquire about
select Field list from Table name where Field like ' Matching condition '; //like Inquire about
select Field list from surface 1, surface 2 where Conditions ...; // Implicit inner join
select Field list from surface 1 [inner] join surface 2 on Connection condition ...; // Explicit inner connection
select Field list from surface 1 left [outer] join surface 2 on Conditions ...; // The left outer join
select Field list from surface 1 right [outer] join surface 2 on Conditions ...; // Right connection
select Field list from surface A Alias A join surface A Alias A on Conditions ...; // Self join
select Field list from surface A... union [all] select Field list from surface B; // The joint query
select * from class where cid=(select classid from student where sname=' Zhang San '); // A subquery with a comparison operator
select * from class where exists (select * from student where sname=' Wang Wu '); // belt EXISTS Subqueries for keywords EXISTS The parameter after the keyword can be any subquery , It does not generate any data, only returns TRUE or FALSE. When the return value is TRUE The outer layer query will perform
select * from class where cid > any (select classid from student); // belt ANY Subqueries for keywords ANY Keyword means that if any of these conditions is met, a result will be returned as the outer query condition .
select * from class where cid > all (select classid from student); // belt ALL Subqueries for keywords belt ALL The result returned from the sub query of keyword must meet all internal query conditions at the same time .
INSERT INTO Table name ( Field name 1, Field name 2,...) VALUES ( value 1, value 2,...); // insert data
INSERT INTO Table name [( Field name 1, Field name 2,...)]VALUES ( value 1, value 2,…),( value 1, value 2,…),...; // Batch insert
UPDATE Table name SET Field name 1= value 1[, Field name 2 = value 2,…] [WHERE Conditional expression ]; // Modifying data
DELETE FROM Table name [WHERE Conditional expression ]; // Delete data
constraint
Field name data type primary key; // Primary key constraint
Field name data type NOT NULL; // Non empty constraint
Field name data type DEFAULT The default value is ; // Default constraint
Field name data type UNIQUE; // Unique constraint
Field name data type check; // Check constraint
-- When creating a data table, the syntax is as follows : // Foreign key constraints
CONSTRAINT Foreign key name FOREIGN KEY ( From the table foreign key field ) REFERENCES Main table ( Primary key field )
-- The syntax after creating the number of the data table is as follows :
ALTER TABLE From the table name ADD CONSTRAINT Foreign key name FOREIGN KEY ( From the table foreign key field ) REFERENCES Main table ( Primary key field );
alter table From the table name drop foreign key Foreign key name ; // Delete foreign key
alter table From the table name drop foreign key Foreign key name foreign key ( Foreign key field ) references // Delete / Update behavior
Main table name ( Main table field name ) on update [no action/restrict/cassade/set null/set default] on delete [no action/restrict/cassade/set null/set default];
function
1. String function
concat,lower,upper,lpad,rpad,trim,substring
2. Numerical function
ceil,floor,mod,rand,round
3. Date function
curdate,curtime,now,year,month,day,date_add,datediff
4. Flow function
if,ifnull,case[...]when...then...else...end;
The transaction operations
select @@autocommit; // View transaction submission method
set @@autocommit; // Set the transaction submission method
commit; // Commit transaction
rollback; // Roll back the transaction
select @@transaction_isolation / select @@tx_isolation; ( The old version ) // View transaction isolation level
set[session|global] transaction level {
read uncommitted|repeatable read|serializable}; // Set the transaction isolation level
Storage engine
create table Table name ( Field 1 Field type , Field 2 Field type ... Field n Field type )engine=innodb; // Create a search engine
show engines; // View the storage engines supported by the current database
alter table Table name type=InnoDB ( The old version ) / alter table Table name ENGINE=InnoDB; // Modify the search engine
Indexes
create [unique|fulltext] index index_name on table_name (index_col_name...); // Create index
show index from table_name; // Look at the index
drop index index_name on table_name; // Delete index
create index idx_xxxx on table_name(column(n)); // Create prefix index column(n)
select count(distinct email)/count(*) from tb_user; select count(distinct substring(email,1,5))/count(*) from tb_user; // Optimal prefix length
sql Optimize
show global status like 'com____'; // see sql Frequency of execution
show variables like 'slow_query_log'; // View the slow query switch
slow_query_log=1; // Turn on slow query
long_query_time=2; // Slow query time setting 2s After that, slow query
select @@have_profiling; // Check whether the database supports profile details
select @@profiling; // see profile Open state of the
show profiles; // see profile Of sql Statement details
set profiling=1; // Set up profile The state of
explain/desc select Field list from Table name where Conditions ; // Get the information of the executed statement
sql Tips
explain select * from tb_user use index(index_user_pro) where profession=' Software Engineering '; //use index; Index is recommended
explain select * from tb_user ignore index(index_user_pro) where profession=' Software Engineering '; //ignore index; Ignore using indexes
explain select * from tb_user force index(index_user_pro) where profession=' Software Engineering '; //force index; Force index
Batch insert optimization
mysql --local-infile -u root -p
set global local_infile=1; // Turn on the switch to import data from the local load file
select @@local_infile; // View the local import data switch status
load data local infile 'D:\\test.txt' into table employee fields terminated by';' lines terminated by '\n'; //load Instructions , Load local file data into the table structure
View
create [or replace] view View name [( view column list )] as select sentence [with[cascaded | local] check option]; // Create view
show create view View name ; // View the create view statement
select * from View name ...; // View view data
Modify the view 1: create [or replace] view View name [( view column list )] as select sentence [with[cascaded | local] check option]; cascaded Will be passed to the upper level of the reference ,local Only apply to the statement
Modify the view 2: alter view View name [( List of names )] as select sentence [with [cascaded | local] check option];
drop view [if exists] View name [, View name ]...; // Delete view
stored procedure
create procedure stored procedure ([ parameter list ]) // Create , If at the command line delimiter $$ Set up sql Statement terminator is $$
begin
--SQL sentence
end;
call name ([ Parameters ]); // call
select * from information_schemaroutines where routine_schema='xxx'; // Query the stored procedure and status information of the specified database
show create procedure Stored procedure name ; // Query the definition of a stored procedure
drop procedure [if exists] Stored procedure name ; // Delete
show [session | global] valables; // See all system variables
show [session | global] variables like '...'; // Fuzzy query of all system variables
select @@[session | global] System variable name ; // View the value of the specified variable
set [session | global] System variable name = value ; // Set system variables
set @@[session | global] System variable name = value ;
set @var_name=expr [,@var_name=expr]...; // assignment
set @var_name:=expr[,var_name:=expr]...;
select @var_name:=expr[,@var_name:=expr]...;
select Field name into @var_name from Table name ;
select @var_name; // Use
local variable
create procedure p2()
begin
declare stu_count int default 0;// Create local variables
select count(*) into stu_count from student;// Assignment variable
select stu_count;// View the result of assignment
end;
call p2();// Use
if Judge
create procedure p3()
begin
declare score int default 58;
declare result varchar(10);
if score>=85 then
set result := ' good ';
elseif score >=60 then
set result := ' pass ';
else
set result := ' fail, ';
end if;
select result;
end;
call p3();
Parameters
create procedure Stored procedure name ([in/out/inout Parameter name Parameter type ])
begin
--SQL sentence
end;
example :
create procedure p4(in score int,out result varchar(10))
begin
if score>=85 then
set result := ' good ';
elseif score >=60 then
set result := ' pass ';
else
set result := ' fail, ';
end if;
end;
call p4(68,@result);
select @result;
case grammar
Grammar 1 :
case case_value
when when_value1 then statement_list1
[when when_value2 then statement_list2]...
[else statement_list]
end case;
Grammar II :
case
when search_condition1 then statement_list1
[when search_condition2 then statement_list2]...
[else statement_list]
end case;
while grammar
while Conditions do
sql Logic
end while;
for example :
create procedure p7(in n int)
begin
declare total int default 0;
while n>0 do
set total:=total+n;
set n:=n-1;
end while;
select total;
end;
repeat grammar // Exit when conditions are met
repeat
sql Logic
until Conditions
end repeat
for example :
create procedure p8(in n int)
begin
declare total int default 0;
repeat
set total := total+n;
set n:=n-1;
until n<0;
end repeat;
select total;
end;
loop grammar
[begin_label:] loop grammar
sql Logic
end loop [end_label];
leave label; -- Exit the currently marked loop body
iterate label; -- Go directly to the next cycle
for example :
create procedure p10(in n int)
begin
declare total int default 0;
sum:loop
if n<=0 then
leave sum;
end if;
if n%2=1 then
set n := n-1;
iterate sum;
end if;
set total := total + n;
set n:n-1;
end loop sum;
end;
The cursor
declare Cursor name cursor for Query statement ; // declare cursor
open Cursor name ; // Open cursor
fetch Cursor name into Variable [, Variable ]; // Get cursor record
close Cursor name ; // Close cursor
Condition handler
declare hander_action handlerfor condition_value [,condition_value]... statement;
hander_action
continue: Continue with the current program
exit: Terminate the execution of the current program
condition_value
sqlstate sqlstate_calue: Status code , Such as 02000
sqlwarning: All with 01 At the beginning sqlstate Code abbreviation
not found: All with 02 At the beginning sqlstate Code abbreviation
sqlexception: All have not been sqlwharning and not found The captured sqlstate Code abbreviation
for example :
create procedure p11(in uage int)
begin
declare uname varchar(100);
declare upro varchar(100);
declare u_cursor cursor for select name,profession from tb_user where age<=uage;
declare exit handler for sqlstate '02000' close u_cursor;
drop table if exists tb_user_pro;
create table if not exists tb_user_pro{
id int primary key auto_increment;
name varchar(100);
profession varchar(100)
};
open u_cursor;
while true do
fetch u_cursor into uname,upro;
insert into tb_user_pro values(null,uname,upro);
end while;
close u_cursor;
trigger
create trigger trigger_name // establish
before/after insert/update/delete on tbl_name for rach row -- Line level triggers
begin
triger_stmt; // Trigger specific logic statement
end;
for example :
create trigger tb_user_insert_trigger
after insert on tb_user for each row
begin
insert into user_logs(id,name) values (null,'insert',new id,new.name);
end;
show trigger; // see
drop trigger [schema_name.]trigger_name; // Delete If there is no designated schema_name, The default is the current database
lock
Global lock
flush tables with readlock; // Set global lock
mysqldump -single-transaction -uroot -p123456 itcast>itcast.sql; // Data consistent backup without lock ( snapshot )
unlock tables; // Unlock the global lock
Table lock
lock tables Table name ... read/write // Lock
unlock tables/ Client disconnected // Release the lock
select...lock in share mode // Intention sharing lock
insert/update/delete/select...for update // Intention exclusive lock
边栏推荐
- 'virtue and art' in the field of recurrent+transformer video recovery
- Servlet API
- token与幂等性问题
- 数据库的三大范式
- h t fad fdads
- 34- [go] golang channel knowledge points
- key为断言的map是怎么玩的
- Joint recruitment notice of ganfei research group of Wuhan University and xuzhenjiang research group of Nanchang University
- <山东大学项目实训>渲染引擎系统(四)
- "Shandong University project training" rendering engine system (8-END)
猜你喜欢
![[research] reading English papers -- the welfare of researchers in English poor](/img/8a/671e6cb6a3f4e3b84ea0795dc5a365.png)
[research] reading English papers -- the welfare of researchers in English poor

idea如何设置导包不带*号

Overview of webrtc's audio network Countermeasures

【湖南大学】考研初试复试资料分享

IDEA在控制台显示出services,统一管理所有的jetty服务,

Double write consistency problem

acwing 801. Number of 1 in binary (bit operation)

大规模实时分位数计算——Quantile Sketches 简史

ISCC-2022 部分wp

Leetcode 2194. Cells within a range in Excel table (yes, solved)
随机推荐
h t fad fdads
Project training of Shandong University rendering engine system (II)
What's the matter with pbootcms' if judgment failure and direct display of labels?
收藏 | 22个短视频学习Adobe Illustrator论文图形编辑和排版
h t fad fdads
GloVe词嵌入(IMDB电影评论情感预测项目实战)
Probation period and overtime compensation -- knowledge before and after entering the factory labor law
Project training of Shandong University rendering engine system (III)
34-【go】Golang channel知识点
<山东大学项目实训>渲染引擎系统(八-完)
The C programming language (version 2) notes / 8 UNIX system interfaces / 8.6 instances (directory list)
Joint recruitment notice of ganfei research group of Wuhan University and xuzhenjiang research group of Nanchang University
ISCC-2022 部分wp
Gopher to rust hot eye grammar ranking
34- [go] golang channel knowledge points
Leetcode 2194. Cellules dans une plage dans un tableau Excel (OK, résolu)
<山东大学项目实训>渲染引擎系统(六)
Iscc-2022 part WP
\begin{algorithm} 笔记
Cookies and sessions