当前位置:网站首页>Review of MySQL knowledge points
Review of MySQL knowledge points
2022-06-29 05:31:00 【Dream demon】
MYSQL Study
install :sudo apt install mysql-server
https://blog.csdn.net/qq_38505969/article/details/109957055
mysql -h Host name -p port -u user name -p password ( Be careful p No space after )
or mysql -u user name -p password
or mysql -u user name -p
-u: user name ,-p: password
sign out :exit、quit、ctrl+d
see mysql process :ps -aux | grep mysql
see mysql Service status :sudo service mysql status
stop it mysql service :sudo service mysql stop
start-up mysql service :sudo service mysql start
restart mysql service :sudo service mysql restart
mysql Profile path :/etc/mysql/mysql.conf.d/mysqld.cnf
View currently used databases :select database();
Delete database :drop database Library name ;
View database creation information :show create database Library name ;
Modify database character set :alter database Library name charset=utf8;
Simply create a data table :create table user(id int,name char(7),age tinyint);
Create standard data tables :create table person(id int(5) unsigned zerofill primary key auto_increment,name char(5) not null,height float(5,2) default 0.0,gender enum(‘ male ’,‘ Woman ’) default ‘ male ’);
View table structure :desc Table name ;
See the information for creating the table :show creat table Table name ;
Add fields to table :alter table Table name add weight float(5,2) not null;
Change the type for the table :alter table Table name modify weight int(5);
Modify the field names and constraints of the table :alter table Table name change weight tizhong float(5,3) default 99.99;
When the field type changes , If there is data in the original field , Then the number string and the number can be converted
You can modify multiple fields and constraints at the same time , Separated by commas .
Delete table fields alter table Table name drop tizhong;
Delete table :drop table Table name ;
Inquire about :
select * from person;
Insert :
insert into Table name values(1,‘tom’,default,male),(2,‘Jack’,178,male); If you don't want to provide data , Also use default placeholder
insert into Table name (name) values(‘Lucy’),(‘Tom’) ;
insert into Table name (id,name,gender) values(5,‘Bulke’,1);
Update data :
update Table name set Field name = value ;
update Table name set Field name = value where Conditions ;
Delete data :
delete from Table name ;
delete from Table name where Conditions ;
Alias :
select id as Serial number ,name as full name ,gender as Gender from person;(as It can be omitted )
Data De duplication :
select distinct name from person;
Fuzzy query :like,%(0 Or more characters ),_( A character ),
select * from person where name like ‘ Grandchildren %’;
select * from person where name like ‘ Grandchildren _’;
select * from person where name like ‘% Grandchildren %’;
Range queries :between…and…( In a continuous range ),in( A discontinuous range )
select * from person where height between 170 and 180;
select * from person where id in (1,7,9);
Empty judgment :is null,is not null
select * from person where height is null;
Be careful :where height is not null; and where not height is null; The results are the same but the execution logic is different , The latter is to take out the empty data first and then invert the selection .
Sort :order by
select * from Table name order by Name asc: Ascending order , Don't write asc Default ascending order
select * from Table name order by Name desc: Descending order
select * from Table name order by Column 1 desc, Column 2 asc: When the same value in column 1 cannot be sorted, use column 2 to sort
where Conditions To write in order by In front of
Paging query :limit,start—— Index start position ,count—— Number of pieces
select * from Table name limit start,count from start+1 Start reading count Data ,start Do not write default is 0,count Show as many as you have when you don't have enough
select * from student limit (n-1)*m,m For the first n Page data
select * from person where gender=‘ Woman ’ order by gender desc limit 5; Query the five oldest people of female sex
where Conditions ——order by——limit
Aggregate functions : Used for statistics and calculation of data
count(col): Find the total row number of the specified column ( Do not count rows with null values )、max(col)、min(col)、sum(col)、avg(col): Average the specified column
round(), Specify the number of decimal places to keep , Such as round(avg(height),2)
select count(height),max(height),min(height),sum(height),avg(height) from person;
It's generally used count(*), Null values can also be counted
ifnull(height,0): If height It's empty , Then use 0 Instead of , Can be used with aggregate functions , Such as count(ifnull(height,0));
Group query :group by
select gender from person group by gender; You can query through any group ——select A from Table name group by A, This method can only see the grouped categories , You can't see the members of each group
group by And group_concat() Use it together to view the members of each group :select gender ,group_concat(name) from person group by gender;
having Filter grouping data (having It can only be used for group by):select gender,group_concat(name) from person where age>50 group by gender having gender=‘ Woman ’; Displays age greater than 50 Name of the female member of
Used with aggregate functions :select gender,count(age),max(age),min(age),sum(age),avg(age) from person where age is not null group by gender;
with rollup:select gender,count(age),max(age),min(age),sum(age),avg(age) from person where age is not null group by gender with rollup; Add a new line after the last record , Show select Statistics and calculation results of aggregate functions during query
Internal connection 、 Left connection 、 The right connection 、 Self connection query where Must be written after the join statement
Internal connection :inner join on according to on The following conditions take the values of two tables “ intersection ”,on Omission
select * from student inner join class; In this case, the number of items queried is student Number of entries in class The product of the number of pieces
select * from student inner join class on student.class_id=class.id; on Following condition
select s.id,s.name,c.class_name class from student as s inner join class c on s.class_id=c.id; as It can be omitted
The left outer join :left join on Mainly in the left table , Query the data in the right table according to the criteria , If the data in the right table does not exist, use null fill ,on Do not omit
select Field from The left table left join Right table on The left table . Field 1= Right table . Field 2;
Right connection :right join on Mainly in the right table , Query the data in the left table according to the criteria , If the data in the left table does not exist, use null fill ,on Do not omit
select Field from The left table right join Right table on The left table . Field 1= Right table . Field 2;
Swap the left table with the right table ,right and left Replace , The result of the left connection query is the same as that of the right connection query
Self join : The left table and the right table are the same table , Internal connection 、 Left connection 、 Right connection can realize self connection
select p.name Provincial name c.name City name from areas p inner join areas c on p.id=c.pid; pid It means the superior place name of the changed place name id
Subquery : The subquery is a complete select sentence , Embed in main query
select * from student where age > (select avg(age) from student); Query students older than the average
select name from class where id in (select distinct class_id from student where class_id is not null); Query which classes students belong to
select * from student where (age,height) = (select max(age),max(height) from student); Find the oldest and tallest student
Foreign key constraints :foreign key(col) reference
When the value of the foreign key field is updated and inserted , The fields in the table will be referenced for data validation , If the data does not conform to the law, it will fail , Ensure the validity of data
A table can have multiple foreign keys
Write directly when creating a table :create table Test(id int(5) not null primary key auto_increment, Field 1 char(5),foreign key( Field 1) references surface 2( Lot 2)); Field 1 And field 2 The type should be consistent , Referenced fields , That is, the fields 2 It must be a watch 2 Primary key of
Be careful : After defining foreign keys , If you want to delete the referenced table or the data in the table , You need to delete the table that defines the foreign key or the data in the table , Just like if you want to dissolve a company , First dismiss the employee . Or delete the foreign key constraint first .
Delete foreign key constraint :
1. Get foreign key name ( Automatic system generation ):show create table Table name ; View foreign key name
2. Delete foreign key constraint :alter table Table name drop foreign key Foreign key name ;
Add a foreign key constraint : If the field 1 There are fields in that cannot be associated with 2 Matching data , Adding a foreign key will fail .
alter table Table name add constraint fk_class_id foreign key( Field 1) references surface 2( Field 2); fk_class_id Is the foreign key name ,constraint fk_class_id It can be omitted , If omitted, the system automatically generates the foreign key name , The foreign key name is usually fk_+ Field name
Insert the query results as data into another table :
insert into … select…; No need to write values()
Use the join to update the data in the table :
update surface 1 inner/left/right join surface 2 on…set…;
When creating a table, add data by querying :create table…select…
create table Table name (id int primary key auto_increment,name char(10) not null) select name from Table name ; perhaps select Field name as name from Table name .id You can omit it , By default, the matching starts from the second field , Be careful :select The field name that follows must be the same as the field name that was added when the table was created .
Business :
A transaction is a series of user-defined executions SQL Statement operation ( increase 、 Delete 、 Change ), All operations in a transaction are either fully performed , Or not at all ( If you exit unexpectedly halfway through the execution, a rollback will occur ), It is an indivisible work execution unit .
Execute the modification instruction after the transaction is started , The changed data will be saved to mysql In the server cache file , Instead of maintaining it in the physical table , Only execute commit Then the data in the local cache file will be submitted to the original physical table , Complete the data update .
Be careful : If not shown, start a transaction , Every one of them sql Statements are treated as a transaction , And because of mysql The default mode is auto submit (autocommit), Therefore, the transaction submission operation will be performed automatically .
set autocommit=0; Indicates that the auto commit transaction mode is canceled , Manual required commit Complete transaction commit ( When a transaction is started , It's automatically set autocommit The value is 0).
The execution of the display commit or rollback Indicates the end of the transaction
Four characteristics :
Atomicity (Atomicity): Emphasize that multiple operations in a transaction are a whole
Uniformity (Consistency): Emphasize keeping consistent state in the database , for example ATM How much do you withdraw when you withdraw money , How much will the balance in the bank card be reduced
Isolation, (Isolation): Emphasize that the operations between multiple transactions in the database are not visible to each other
persistence (Durability): Emphasize that the database can store data permanently , Once submitted, it is irrevocable
Only InnoDB The engine can use transactions , The common table storage engine is InnoDB and MyISAM,MyISAM Unsupported transaction , The advantage is fast access .
Modify the storage engine of the table :alter table Table name engine=‘MyISAM’;
Operation of transaction :
sql sentence :
Open transaction begin; or start transaction;
Commit transaction commit;
Roll back the transaction rollback;
After committing or rolling back a transaction , The current transaction will end
pymysql:
Connect to database objects .cursor() Create cursor object , Automatically and implicitly start a transaction
Commit transaction : Connect to database objects .commit()
Roll back the transaction : Connect to database objects .rollback()
Indexes :
stay mysql Also known as ” key “, It's a special document , Keep all the location information recorded in the data sheet , It's like a book catalog , Can speed up the query speed of the database .
show index from Table name ; Look at the index ( The primary key column will automatically create an index )
alter table test_index add index idx_title(title); Create index ( It's very time consuming ), The name of a non unique index is generally set to idx_+ Field name , If you do not write, the default is the field name , After adding the index , Use where You only need to compare the data once .
Add... Before the query statement desc By looking at rows Property value to view the number of comparisons ,Extra Property value view query method
alter table test_index drop index idx_title; Delete index
set profiling=1; Start time monitoring
show profiles; View the recorded data of time monitoring
Joint index ( Composite index ): An index covers two or more fields in a table , It is generally used when multiple fields are queried together
alter table Table name add index [ Index name ] ( Field 1, Field 2,…);
The principle of left : If ( Field 1, Field 2, Field 3) Create a federated index , Then at the same time, it will give ( Field 1)、( Field 1, Field 2) Create index
The advantage is that the overhead of disk space is reduced , The disadvantage is that it takes a long time
The principle of using index :
1. Avoid creating too many indexes for frequently updated tables , Because updating the index is very time-consuming , You should create an index on frequently queried fields
2. It is better not to create an index for a table with a small amount of data
3. Do not create an index when there are many same values in the same field , for example “ Gender ” Field
4. The more indexes, the better , A comprehensive trade-off should be made between the query speed and the time and space occupied by indexing
边栏推荐
- Tcapulusdb Jun · industry news collection (VI)
- Robot reinforcement learning -- first person vs third person
- 5000+ word interpretation | Product Manager: how to do a good job in component selection?
- Analysis of ArrayList set in teacher Yang's class
- Distributed transaction Seata
- How to use thread stack location
- [code Capriccio - dynamic planning] longest common subsequence
- How to choose congestion model and anemia model
- Analysis report on the investment market of the development planning prospect of the recommended rare earth industry research industry in 2022 (the attachment is a link to the online disk, and the rep
- Le langage C imprime "Love", "Mars hit Earth" et ainsi de suite en utilisant printf, qui est constamment mis à jour
猜你喜欢

Test content

Use VS to create a static link library Lib and use

How to choose congestion model and anemia model

Manual (functional) test 1

没遇到过这三个问题都不好意思说用过Redis

Top ten Devops best practices worthy of attention in 2022

2022 recommended quantum industry research industry development planning prospect investment market analysis report (the attachment is a link to the online disk, and the report is continuously updated
![[IOT] description of renaming the official account](/img/54/43189f34b81a7441cd46d5c2066970.png)
[IOT] description of renaming the official account "Jianyi commerce" to "product renweipeng"

The fresh student who was born in Ali after 2000: it's really fragrant to mend this

2022 recommended property management industry research report industry development prospect market investment analysis (the attachment is the link to the online disk, and the report is continuously up
随机推荐
Output various graphics and text on the console through C #
5000+ word interpretation | Product Manager: how to do a good job in component selection?
Parsing rshub document auto generation API
Research Report on global market segmentation based on condition based maintenance (CBM) overall scale, major enterprises, major regions, products and applications in 2022
Embedded RTOS
Research Report on the overall scale, major manufacturers, major regions, products and applications of magnetron sputtering coaters in the global market in 2022
5000+ 字解读 | 产品经理:如何做好元器件选型?
Annual inventory review of Alibaba cloud's observable practices in 2021
Accelerate the global cloud native layout, kyligence intelligent data cloud officially supports Google cloud
Research Report on the overall scale, major manufacturers, major regions, products and applications of high temperature film capacitors in the global market in 2022
Direct derivation of Bessel function with MATLAB
HTTP Caching Protocol practice
(practice C language every day) matrix
How to choose congestion model and anemia model
Robot reinforcement learning -- first person vs third person
be based on. NETCORE development blog project starblog - (13) add friendship link function
Common optimization items
2022 community group buying industry research industry development planning prospect investment market analysis report (the attachment is the online disk link, and the report is continuously updated)
Analysis report on the investment market of the development planning prospect of the recommended wind power industry research industry in 2022 (the attachment is a link to the network disk, and the re
Tcapulusdb Jun · industry news collection (III)