当前位置:网站首页>MySQL notes

MySQL notes

2022-06-22 04:39:00 Born as a worm

mysql

Connection related commands

sqlserver Qi / stop

net start  service name 
net stop  service name 

Connect to database

mysql  -h   Host name (ip)  -u   user name  -P  port  -p 

View connections

SHOW PROCESSLIST;

Check the port

SHOW GLOBAL VARIABLES LIKE 'port'

View the auto increment primary key and set the starting value

SHOW VARIABLES LIKE 'auto_increment%';
ALTER TABLE url AUTO_INCREMENT = 506;

User related commands

A new user

#-- Created a new one called :spiders  The password for :spiders Users of 
 CREATE USER 'spiders'@'localhost' IDENTIFIED BY 'spiders';
#  Be careful :
# Here "localhost", It means that the user can only log in locally , Can't log in remotely on another machine . If you want to log in remotely ,
# take "localhost" Change it to "%", It means that you can log in to any computer . You can also specify that a machine can log in remotely .
 CREATE USER 'db_user'@'%' IDENTIFIED BY '[email protected]';

Query the user

SELECT USER,HOST FROM mysql.user;

Delete user

1DELETE FROM mysql.user WHERE USER = "hushen" AND HOST = "localhost" ;

2#-- Delete user “test”
DROP USER test@localhost ;
#-- If the created user allows any computer to log in , Delete the user as follows 
DROP USER test@'%';

User assigned permissions

#-- Grant users test Through the Internet IP To the database “testdb” All permissions for 
GRANT ALL PRIVILEGES ON testdb.* TO 'test'@'%' WITH GRANT OPTION;

#-- Grant users “test” Through the Internet IP For this database “testdb” Creation of tables in 、 modify 、 Delete permission , And the authority to add, delete, query and modify table data 
GRANT CREATE,ALTER,DROP,SELECT,INSERT,UPDATE,DELETE ON testdb.* TO test@'%';	
#-- Refresh the permissions 
FLUSH PRIVILEGES;

View permissions

#4. View user permissions 
#-- To view the user “test”
SHOW GRANTS FOR test;

Change password

#-- Method 1, Real time password update ; Modify the user “test” The password for “1122”
SET PASSWORD FOR test =PASSWORD('1122');
#-- Method 2, Need to refresh ; Modify the user “test” The password for “1234”
UPDATE  mysql.user SET  PASSWORD=PASSWORD('1234')  WHERE USER='test'
#-- Refresh 
FLUSH PRIVILEGES;

If sqlyog Unable to connect through user name and password. You need to modify the encryption rules and reset the password

# Modify encryption rules 
ALTER USER 'db_user'@'%' IDENTIFIED BY '[email protected]' PASSWORD expire never;
# Change Password 
ALTER USER 'db_user'@'%' IDENTIFIED WITH mysql_native_password BY '[email protected]';

Basic query

One 、 grammar

select  Query list  from  Table name ;

Two 、 characteristic
1、 The query list can be a field 、 Constant 、 expression 、 function , It can be multiple
2、 The query result is a virtual table

3、 ... and 、 Example
1、 Query a single field

select  Field name  from  Table name ;

2、 Query multiple fields

select  Field name , Field name  from  Table name ;

3、 Query all fields

select * from  Table name 

4、 Query constants

select  Constant values ;
 Be careful : Constant values of character type and date type must be enclosed in single quotation marks , Numeric not required 

5、 Query function

select  Function name ( Argument list );

6、 Query expression

select 100/1234;

7、 names
①as
② Space

8、 duplicate removal

select distinct  Field name  from  Table name ;

9、+
effect : add
select The number + The number ; Direct operation
select character + The number ; Try to convert the character to a numeric value first , If the conversion is successful , Then continue to calculate ; Otherwise, it will be converted into 0, Re operation
select null+ value ; The result is null

10、【 Add 】concat function
function : Concatenate characters

select concat( character 1, character 2, character 3,...);

11、【 Add 】ifnull function
function : Determine whether a field or expression is null, If null Returns the specified value , Otherwise, return the original value

select ifnull(commission_pct,0) from employees;

12、【 Add 】isnull function
function : Determine whether a field or expression is null, If it is , Then return to 1, Otherwise return to 0

Conditions of the query

One 、 grammar

select  Query list  from  Table name  where  filter 

Two 、 Classification of filter conditions
1、 Simple conditional operators

< = <> != >= <= <=> Safety is equal to

2、 Logical operators
&& and
|| or
! not

3、 Fuzzy query
like: Generally used with wildcards , You can judge character type or numeric type
wildcard :% Any number of characters ,_ Any single character

between and
in
is null /is not null: Used to judge null value

is null PK <=>

is null PK <=>
			 Common types of values 	null value 		 Readability 
is null		      ×			 √		     √
<=>		          √			 √		     ×

Sort query

One 、 grammar

select  Query list  
from  surface 
where  filter 
order by  Sort list  【asc}desc

Two 、 characteristic

1、asc : Ascending , If you don't write the default ascending order
desc: Descending

2、 Sort list Support Single field 、 Multiple fields 、 function 、 expression 、 Alias

3、order by The position of is usually placed at the end of the query statement ( except limit Statements in )

Common function

One 、 summary
function : Be similar to java The method in
benefits : Improve reusability and hide implementation details
call :select Function name ( Argument list );
Two 、 One line function
1、 Character functions
concat: Connect
substr: Intercept substring
upper: Capitalize
lower: Change to lowercase
replace: Replace
length: Get the byte length
trim: Space before and after
lpad: padding-left
rpad: Right fill
instr: Get the index of the first occurrence of the substring
2、 Mathematical functions
ceil: Rounding up
round: rounding
mod: modulus
floor: Rounding down
truncate: truncation
rand: Get random numbers , return 0-1 Decimal between

3、 Date function

now: Return current date + Time
year: Year of return
month: Return month
day: Return day
date_format: Convert date to character
curdate: Return current date
str_to_date: Convert characters to dates
curtime: Return current time
hour: Hours
minute: minute
second: second
datediff: Returns the number of days between two dates
monthname: Returns the month in English

4、 Other functions
version The version of the current database server
database Currently open database
user The current user
password(‘ character ’): Returns the password form of the character
md5(‘ character ’): Returns the md5 Encryption form

5、 Process control functions

①if( Conditional expression , expression 1, expression 2): If the conditional expression holds , Return expression 1, Otherwise return the expression 2
②case situation 1
case Variables or expressions or fields
when Constant 1 then value 1
when Constant 2 then value 2

else value n
end

③case situation 2
case
when Conditions 1 then value 1
when Conditions 2 then value 2

else value n
end

3、 ... and 、 Group function
1、 classification
max Maximum
min minimum value
sum and
avg Average
count Calculate the number of

2、 characteristic

① grammar
select max( Field ) from Table name ;

② Types of support
sum and avg Generally used to deal with numerical type
max、min、count Can handle any data type

③ All the above grouping functions are ignored null
④ Can be matched with distinct Use , Realize the statistics of de duplication
select sum(distinct Field ) from surface ;
⑤count function
count( Field ): Count the number of non null values in this field
count(*): Counts the number of rows in the result set
Case study : Query the number of employees in each department
1 xx 10
2 dd 20
3 mm 20
4 aa 40
5 hh 40

count(1): Counts the number of rows in the result set

Efficiency :
MyISAM Storage engine ,count() The highest
InnoDB Storage engine ,count(
) and count(1) efficiency >count( Field )

⑥ Fields to query with grouping function , The requirement is group by Fields after

Group query

One 、 grammar
select Group function , Fields after grouping
from surface
【where filter 】
group by Grouped fields
【having Screening after grouping 】
【order by Sort list 】

Two 、 characteristic

Use keywords Filtered table Location
Filter before grouping where Original table group by In front of
Filter after grouping having Results after grouping group by Behind

Link query

One 、 meaning
When multiple table fields are involved in the query , You need to use multi table connection
select Field 1, Field 2
from surface 1, surface 2,…;

Cartesian product : When querying multiple tables , No valid connection conditions added , Causes all rows of multiple tables to be fully joined
How to solve : Add valid connection conditions

Two 、 classification

By age :
sql92:
equivalence
non-equivalence
Self join

	 It also supports some external connections ( be used for oracle、sqlserver,mysql I won't support it )
sql99【 Recommended 】
	 Internal connection 
		 equivalence 
		 non-equivalence 
		 Self join 
	 External connection 
		 Left lateral 
		 Right outside 
		 Total external (mysql I won't support it )
	 Cross connect 

3、 ... and 、SQL92 grammar
1、 Equivalent connection
grammar :
select Query list
from surface 1 Alias , surface 2 Alias
where surface 1.key= surface 2.key
【and filter 】
【group by Grouping field 】
【having Screening after grouping 】
【order by Sort field 】

characteristic :
① It's usually a table alias
② The order of multiple tables can be changed
③n At least... Is required for meter connection n-1 Connection conditions
④ The result of equivalence join is the intersection part of multiple tables

2、 Non equivalent connection
grammar :
select Query list
from surface 1 Alias , surface 2 Alias
where Non equivalent connection conditions
【and filter 】
【group by Grouping field 】
【having Screening after grouping 】
【order by Sort field 】
3、 Self join

grammar :
select Query list
from surface Alias 1, surface Alias 2
where Equivalent connection conditions
【and filter 】
【group by Grouping field 】
【having Screening after grouping 】
【order by Sort field 】

Four 、SQL99 grammar
1、 Internal connection
grammar :
select Query list
from surface 1 Alias
【inner】 join surface 2 Alias on Connection condition
where filter
group by Group list
having Screening after grouping
order by Sort list
limit Clause ;

characteristic :
① The order of the tables can be changed
② The result of internal connection = The intersection of multiple tables
③n At least... Is required for meter connection n-1 Connection conditions

classification :
Equivalent connection
Non equivalent connection
Self join

2、 External connection
grammar :
select Query list
from surface 1 Alias
left|right|full【outer】 join surface 2 Alias on Connection condition
where filter
group by Group list
having Screening after grouping
order by Sort list
limit Clause ;
characteristic :
① Result of query = All rows in the main table , If you match it from the table, the matching row will be displayed , If there is no match from the table, display null
②left join On the left is the main table ,right join On the right is the main table
full join There are main tables on both sides
③ It is generally used to query the remaining mismatched rows except the intersection part

3、 Cross connect

grammar :
select Query list
from surface 1 Alias
cross join surface 2 Alias ;

characteristic :
It's like Cartesian product

Common cases

sql Inquire about : There is A Watch but not B Table data 
A、B The two tables , find ID Field , There is A surface , But it doesn't exist B The data table .
 Method 1 :
 Use  not in
select distinct A.ID from A where A.ID not in (select ID from B)
 Non empty query 
SELECT * FROM A WHERE A.Id IS NOT NULL AND (A.Id NOT IN (SELECT Id FROM B WHERE Id IS NOT NULL))
 Method 2 :
 Use  left join...on... , "B.ID isnull"  After the left connection B.ID  Field is  null The record of 
select A.ID from A left join B on A.ID=B.ID where B.ID is null
 Method 3 :
select * from B where (select count(1) as num from A where A.ID = B.ID) = 0

Subquery

One 、 meaning
Nested inside other statements select Statements are called subqueries or intra queries ,
The outside statement can be insert、update、delete、select etc. , commonly select As an external statement, there are more
If the outside is select sentence , Then this statement is called external query or main query

Two 、 classification
1、 Press where it appears
select Back :
Only scalar subqueries are supported
from Back :
Table sub query
where or having Back :
Scalar subquery
Column query
Line sub query
exists Back :
Scalar subquery
Column query
Line sub query
Table sub query

2、 By row and column of the result set
Scalar subquery ( Single line sub query ): The result set is row by column
Column query ( Multi line sub query ): The result set is multiple rows and one column
Line sub query : The result set is multi row and multi column
Table sub query : The result set is multi row and multi column

3、 ... and 、 Example
where or having Back
1、 Scalar subquery
Case study : Query the name and salary of the minimum wage employee
① minimum wage
select min(salary) from employees

② Check the employee's name and salary , Ask for salary =①
select last_name,salary
from employees
where salary=(
select min(salary) from employees
);

2、 Column query
Case study : Query the names of all employees who are leaders
① Check the information of all employees manager_id
select manager_id
from employees

② Search for names ,employee_id Belong to ① A of the list
select last_name
from employees
where employee_id in(
select manager_id
from employees
);

Paging query

One 、 Application scenarios
When there are too many entries to query , One page is incomplete
Two 、 grammar

select Query list
from surface
limit 【offset,】size;
Be careful :
offset Represents the initial entry index , The default from the 0 stuck
size Represents the number of items displayed

The formula :
If the number of pages to be displayed is page, The number of entries on each page is size
select Query list
from surface
limit (page-1)*size,size;

The joint query

One 、 meaning
union: Merge 、 union , Combine multiple query results into one result
Two 、 grammar
Query statement 1
union 【all】
Query statement 2
union 【all】

3、 ... and 、 significance
1、 Split a more complex query statement into multiple statements
2、 When querying multiple tables , The columns of the query are basically the same

Four 、 characteristic
1、 It is required that the number of query columns of multiple query statements must be consistent
2、 Each column type of a query that requires multiple query statements 、 It's better to have the same order
3、union duplicate removal ,union all Include duplicates

Query summary

grammar :
select Query list ⑦
from surface 1 Alias ①
Connection type join surface 2 ②
on Connection condition ③
where Screening ④
group by Group list ⑤
having Screening ⑥
order by Sort list ⑧
limit Start entry index , Number of entries ; ⑨

Insert

One 、 Mode one
grammar :

insert into  Table name ( Field name ,...) values( value ,...);

characteristic :
1、 The type of value and field should be consistent or compatible
2、 The number and order of fields are not necessarily the same as those in the original table
However, you must ensure that the values and fields correspond one-to-one
3、 If there is one in the table, it can be null Field of , Note that you can insert it in two ways null value
① Fields and values are omitted
② Write in the field , Value usage null
4、 The number of fields and values must be the same
5、 Field names can be omitted , Default all columns

Two 、 Mode two
grammar :

insert into  Table name  set  Field = value , Field = value ,...;

Two ways The difference between :
1. Method one supports inserting multiple lines at a time , The grammar is as follows :
insert into Table name 【( Field name ,…)】 values( value ,…),( value ,…),…;
2. Mode 1 supports subquery , The grammar is as follows :
insert into Table name
Query statement ;

modify

One 、 Record of modification list *
grammar :

update  Table name  set  Field = value , Field = value  【where  filter 】;

Two 、 Modify multi table records 【 Add 】
grammar :

update  surface 1  Alias  
left|right|inner join  surface 2  Alias  
on  Connection condition   
set  Field = value , Field = value  
【where  filter 】;

Delete

Mode one : Use delete
One 、 Delete a single table record *
grammar :delete from Table name 【where filter 】【limit Number of entries 】
Two 、 cascading deletion [ Add ]
grammar :
delete Alias 1, Alias 2 from surface 1 Alias
inner|left|right join surface 2 Alias
on Connection condition
【where filter 】

Mode two : Use truncate
grammar :truncate table Table name

The difference between the two ways 【 Interview questions 】*

1.truncate After deleting , If you insert , Identity column from 1 Start
delete After deleting , If you insert , The identity column starts at the breakpoint
2.delete You can add filter criteria
truncate Cannot add filter criteria
3.truncate More efficient
4.truncate no return value
delete You can return the number of affected rows
5.truncate You can't roll back
delete You can roll back

Library management

One 、 Create a library
create database 【if not exists】 Library name 【 character set Character set name 】;

Two 、 Modify Library
alter database Library name character set Character set name ;
3、 ... and 、 Delete Library
drop database 【if exists】 Library name ;

The management of the table

One 、 Create table *
create table 【if not exists】 Table name (
Field name Field type 【 constraint 】,
Field name Field type 【 constraint 】,
...
Field name Field type 【 constraint 】

)

Two 、 Modify table

1. Add columns
alter table Table name add column Name type 【first|after Field name 】;
2. Modify the type or constraint of the column
alter table Table name modify column Name new type 【 New constraint 】;
3. Change column names
alter table Table name change column Old column names New column names type ;
4 . Delete column
alter table Table name drop column Name ;
5. Modify the name of the table
alter table Table name rename 【to】 The new name of the table ;

3、 ... and 、 Delete table
drop table【if exists】 Table name ;

Four 、 Copy table
1、 Copy the structure of the table
create table Table name like Old table ;
2、 Copy the structure of the table + data
create table Table name
select Query list from Old table 【where Screening 】;

Copy table

# Copy table 
1、 Replicated table structure 
CREATE TABLE  Table name  LIKE  Old table ; 
CREATE TABLE test LIKE url;
2、 Replicated table structure + data 
CREATE TABLE  Table name  
SELECT  Query list  FROM  Old table 【where  Screening 】;
CREATE TABLE test1 SELECT * FROM url;

data type

One 、 Numerical type
1、 integer
tinyint、smallint、mediumint、int/integer、bigint
1 2 3 4 8

characteristic :
① Both unsigned and signed can be set , Default signed , adopt unsigned Set up unsigned
② If it's out of range , Will be submitted to the out or range abnormal , Insert threshold
③ The length may not be specified , There will be a length by default
The length represents the maximum width of the display , If not enough, use... On the left 0 fill , But it needs to match zerofill, And default to unsigned integer

2、 floating-point
Fixed-point number :decimal(M,D)
Floating point numbers :
float(M,D) 4
double(M,D) 8

characteristic :
①M Represents the integral part + The number of decimal parts ,D Represents the decimal part
② If you go out of range , Then newspaper out or range abnormal , And insert the critical value
③M and D All can be omitted , But for fixed-point numbers ,M The default is 10,D The default is 0
④ If the accuracy is high , The fixed-point number is preferred

Two 、 Character
char、varchar、binary、varbinary、enum、set、text、blob

char: Fixed length characters , It's written as char(M), The maximum length cannot exceed M, among M It can be omitted , The default is 1
varchar: Variable length characters , It's written as varchar(M), The maximum length cannot exceed M, among M Don't omit

3、 ... and 、 Date type
year year
date date
time Time
datetime date + Time 8
timestamp date + Time 4 More vulnerable to time zone 、 Grammatical pattern 、 The impact of the version , Better reflect the real time in the current time zone

Common constraints

One 、 Common constraints
NOT NULL: Non empty , The value of this field is required
UNIQUE: only , The value of this field cannot be repeated
DEFAULT: Default , The value of this field does not need to be manually inserted. There is a default value
CHECK: Check ,mysql I won't support it
PRIMARY KEY: Primary key , The value of this field cannot be repeated and is not empty unique+not null
FOREIGN KEY: Foreign keys , The value of this field refers to the field of another table

Primary key and unique
1、 difference :
①、 A table can have at most one primary key , But there can be multiple unique
②、 Primary key cannot be empty , The only one can be empty
2、 The same thing
They are all unique
All support key combinations , But it is not recommended.
Foreign keys :
1、 Used to restrict the relationship between two tables , The field value of the slave table refers to a field value of the main table
2、 The foreign key column and the referenced column of the main table must be of the same type , It means the same thing , Name is not required
3、 The referenced column of the main table is required to be a key( It's usually the primary key )
4、 insert data , Insert the main table first
Delete data , First delete from table
You can delete records in the main table in the following two ways
# Mode one : cascading deletion
ALTER TABLE stuinfo ADD CONSTRAINT fk_stu_major FOREIGN KEY(majorid) REFERENCES major(id) ON DELETE CASCADE;

# Mode two : Cascade empty
ALTER TABLE stuinfo ADD CONSTRAINT fk_stu_major FOREIGN KEY(majorid) REFERENCES major(id) ON DELETE SET NULL;

Two 、 Add constraints when creating tables
create table Table name (
Field name Field type not null,# Non empty
Field name Field type primary key,# Primary key
Field name Field type unique,# only
Field name Field type default value ,# Default
constraint Constraint name foreign key( Field name ) references Main table ( The referenced column )

)
Be careful :
Support type You can call it a constraint name
Column level constraints Except for foreign keys Can not be
Table level constraints Except for non null and default Sure , But not for primary key

Column level constraints can append multiple , Space separates the middle , No sequence required

3、 ... and 、 Add or remove constraints when modifying tables
1、 Non empty
Add non empty
alter table Table name modify column Field name Field type not null;
Delete non empty
alter table Table name modify column Field name Field type ;

2、 Default
Add default
alter table Table name modify column Field name Field type default value ;
Delete default
alter table Table name modify column Field name Field type ;
3、 Primary key
Add primary key
alter table Table name add【 constraint Constraint name 】 primary key( Field name );
Delete primary key
alter table Table name drop primary key;

4、 only
Add unique
alter table Table name add【 constraint Constraint name 】 unique( Field name );
Delete unique
alter table Table name drop index Index name ;
5、 Foreign keys
Add foreign keys
alter table Table name add【 constraint Constraint name 】 foreign key( Field name ) references Main table ( The referenced column );
Delete foreign key
alter table Table name drop foreign key Constraint name ;

Four 、 Self growth column
characteristic :
1、 You don't have to insert values manually , Sequence values can be provided automatically , The default from the 1 Start , In steps of 1
auto_increment_increment
If you want to change the starting value : Insert values manually
If you want to change the step size : Change system variables
set auto_increment_increment= value ;
2、 A table can have at most one self growing column
3、 Self growing columns can only support numeric types
4、 The self growth column must be a key

One 、 Set self growing columns when creating tables
create table surface (
Field name Field type constraint auto_increment
)
Two 、 Set self growing columns when modifying tables
alter table surface modify column Field name Field type constraint auto_increment
3、 ... and 、 Delete self growing Columns
alter table surface modify column Field name Field type constraint

Business

One 、 meaning
Business : One or more sql Statements form an execution unit , A group of sql Statements are either executed or not executed
Two 、 characteristic (ACID)
A Atomicity : A transaction is an indivisible whole , Either all or none
C Uniformity : A transaction can switch data from one consistent state to another consistent state
I Isolation, : One transaction is not disturbed by other transactions , Multiple transactions are isolated from each other
D persistence : Once a transaction is committed , Then it will be permanently persisted locally

3、 ... and 、 Use steps of transaction *
understand :
Implicit ( Automatically ) Business : No obvious opening and ending , Itself is a transaction that can be automatically committed , such as insert、update、delete
Explicit transaction : With obvious opening and ending

Use explicit transactions :
① Open transaction
set autocommit=0;
start transaction;# It can be omitted

② Write a set of logic sql sentence
Be careful :sql Statement supports insert、update、delete

Set rollback point :
savepoint Roll back roll call ;

③ End the business
Submit :commit;
Roll back :rollback;
Roll back to the specified place :rollback to Roll back roll call ;
Four 、 Concurrent transactions
1、 How does the concurrency of transactions happen ?
Multiple transactions meanwhile operation When the same data of the same database
2、 What are the concurrent problems ?
Dirty reading : A transaction reads data that has not been committed by other transactions , Read about other things “ to update ” The data of
It can't be read repeatedly : A transaction reads more than once , The results are different
Fantasy reading : A transaction reads data that has not been committed by other transactions , Just read that Other business “ Insert ” The data of
3、 How to solve the concurrent problem
Solve the concurrency problem by setting the isolation level
4、 Isolation level
Dirty reading It can't be read repeatedly Fantasy reading
read uncommitted: Read uncommitted × × ×
read committed: Read submitted √ × ×
repeatable read: Repeatable √ √ ×
serializable: Serialization √ √ √

performance optimization

sql Performance view

EXPLAIN SELECT * FROM url WHERE id=1;

Question collection

solve cmd Command Chinese garbled

set names gbk;
原网站

版权声明
本文为[Born as a worm]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220437266228.html