当前位置:网站首页>[Database Foundation] summary of MySQL Foundation
[Database Foundation] summary of MySQL Foundation
2022-07-25 23:29:00 【zwhnsh】
1、MySql Start up and connect
Server startup :
- see mysql state :sudo /etc/init.d/mysql status
- Start the service :sudu /etc/init.d/mysql start | stop | restart
Client connection :
Command format :
mysql -h The host address -u user name -p password , Such as :
mysql -hlocalhost -uroot -p123456, Local connections can be omitted -h Options :mysql -uroot -p123456
Close the connection :
- quit
- exit
2、 Database operation
2.1、 View existing libraries
show databases; -- Keywords are not case sensitive , Parameter differentiation
2.2、 Create a library ( Specify character set )
create database Library name [character set utf8];
create database test_book character set utf8; -- or
create database test_book character=utf8;
2.3、 View character set
show create database stu;
2.4、 View the current library
select database();
2.5、 Switch Library
use stu;
2.6、 Delete Library
drop database test;
3、 Data table management
3.1、 Data type support
3.1.1、 Numeric type
Integer types :
TINYINT:1 byte
SMALLINT:2 byte
MEDIUMINT:3 byte
INT:4 byte
BIGINT:8 byte
Floating point type :
FLOAT:4 byte
DOUBLE:8 byte
Point type :DECIMAL(M,D)
M Is the maximum number of digits in a number , Range 1-65, The default value is 10
D Is the number of digits to the right of the decimal point , Range 0-30, No more than M
Such as :DECIMAL(6,2), Save at most 6 Digit number , After the decimal point 2 position , The scope is -9999.99~9999.99
Bit value type :BIT
0,1 Values express two situations , Ruzhen , false
3.1.2、 String type
CHAR and VARCHAR type
- CHAR: Fixed length (0-255 byte ), Efficient , Default 1 character ,CHAR(32) Even if the string length is less than 32 Will also open up 32 Byte space . If the length is not specified , The default is 1
- VARCHAR(0-65535 byte ): Indefinite length , Low efficiency ,VARCHAR(32) It means to develop according to the actual situation , most 32 byte . Length... Must be specified .
BLOB type
- TINYBLOB: Storage 2 Base string (0-255 byte ), For example, you can save pictures ;
- BLOB:0-65535 byte
- MEDIUMBLOB:0-16777215 byte
- LONGBLOB:0-4294967295 byte
- TEXT Storing text data ,
TEXT type
- TINYTEXT: Text string (0-255 byte ), and VARCHAR The difference is that there is no need to specify the length
- TEXT:0-65535 byte
- MEDIUMTEXT:0-16777215 byte
- LONGTEXT:0-4294967295 byte
3.1.3、ENUM The type and SET type
- ENUM Enumeration type , Used to store a given value
- SET Collection types , Used to store one or more given values
3.1.4、 Date time type
- DATA:YYYY-MM-DD, Such as :2022-06-15
- TIME:HH:MM:SS, Such as :17:35:22
- YEAR:YYYY, Such as :2022
- DATATIME:YYYY-MM-DD HH:MM:SS,8 byte , The scope is 1000-01-01 00:00:00~9999-12-31 23:59:59, Such as :2022-06-15 17:35:22
- TIMESTAMP:YYYY-MM-DD HH:MM:SS,4 byte , The scope is 1970-01-01 00:00:01 UTC~2038-01-19 03:14:07 UTC, Such as :2022-06-15 17:35:22
Commonly used date time function :
now() Returns the current time of the server ,datetime,YYYY-MM-DD HH:MM:SS
curdate() Return current date ,date,YYYY-MM-DD, If the data type is datetime, Then for YYYY-MM-DD 00:00:00
curtime() Return current time ,time,HH:MM:SS, If the data type is datetime, Then the date will be automatically supplemented with the current date
date(date) Returns the date at the specified time ,date
time(date) Returns the time of the specified time ,time
Date time operation :
Grammar format :
select * from Table name where Field name Operator ( Time -interval Time interval unit );
Time interval unit :1 day | 2 hour | 1 minute | 2 year |3 month
select * from xxx_table where shijian > now() - interval 1 day;
3.2、 Basic operation of the watch
3.2.1、 Create table
create table Table name (
Field name data type ,
Field name data type ,
…
Field name data type
)
tips:
If you want to set the number to unsigned, add UNSIGNED
If you don't want the field to be NULL You can set the field attribute to NOT NULL
DEFAULT Indicates setting the default value of a field
AUTO_INCREMENT Define the column as a self incrementing attribute , Generally used for primary key , The value will automatically increase by one
PRIMARY KEY Keywords are used to define columns as primary keys , The primary key value cannot be duplicate
Examples are as follows :
CREATE TABLE book(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(32) NOT NULL,
type SET(' literature ',' history ',' Geography ',' Physics ',' mathematics '),
public ENUM(' People's Literature Press ',' Electronic industry press ',' Mechanical industry press ',' Peking University press '),
price decimal(7,2),
introduce text,
upt datetime default now()
);
3.2.2、 See the table
show tables;
3.2.3、 View the character set of the existing table
show create table Table name ;
3.2.4、 View table structure
desc Table name ;
3.2.5、 Delete table
drop table Table name ;
4、 Data basic operation
4.1、 Insert insert
insert into Table name values( value 1, value 2, value 3...); -- When no field is specified , All fields should be set with values
insert into Table name ( Field 1, Field 2,...) values( value 1, value 2,...);
e.g.
insert into book values (1,' Long song line ',' literature , history ',' Peking University press ',52.2,' Tang legend ',now());
-- set use ',' separate
give the result as follows :
+----+--------+-----------+----------------+-------+--------------+---------------------+
| id | name | type | public | price | introduce | upt |
+----+--------+-----------+----------------+-------+--------------+---------------------+
| 1 | Long song line | literature , history | Peking University press | 52.20 | Tang legend | 2022-06-15 16:06:26 |
+----+--------+-----------+----------------+-------+--------------+---------------------+
4.2、 Inquire about select
select * from Table name [where Conditions ];
select Field 1, Field 2 Table name [where Conditions ];
where Clause : Data filtering through certain operation conditions
select * from book where id % 2 = 1;
-- lookup id All data with odd numbers
select * from book where find_in_set(' history ',type);
-- lookup type contain ' history ' All data for
select * from book where public like '__ university %';
--like For fuzzy query ,'_' Matches any character ,'%' Match any number of characters
4.3、 to update update
update Table name set Field 1= value 1, Field 2= value 2,... where Conditions ;
e.g:
update book set price=38.8 where id=1;
4.4、 Delete delete
delete from Table name where Conditions ;
e.g:
delete from book where id=8;
5、 Table field operation
grammar :alter table Table name Executive action ;
Change data type :modify
Table rename
alter table Table name rename The new name of the table
e.g.
alter table class add tel char(11) not null; // Add to the end
alter table class add height int after age; // Add to age after
alter table class add test int first; // Add to beginning
alter table class drop test;
alter table class modify height char(3);
alter table class change height weight int;
alter table class rename classnew;
5.1、 Add fields :add
alter table Table name add Field name data type ; -- Add... At the end
alter table Table name add Field name data type first; -- Add... At the beginning
alter table Table name add Field name data type after Field name ; -- Add... After a field
5.2、 Delete field :drop
alter table Table name drop Field name ;
5.3、 Modify field name :change
alter table Table name change Old field name new field name New data types ;
5.3、 Change data type :modify
alter table Table name modify Field name New data types ;
5.4、 Table rename :rename
alter table Table name rename The new name of the table ;
6、 Advanced query
6.1、 Regular queries :REGEXP
- Regular queries :regexp, Only some regular metacharacters are supported
select *
from table_name
where field1 regexp condition1;
-- e.g:
select * from book where public regexp '.*? north .*?';
6.2、 Sort :ORDER BY
select * from book order by id; -- Default ascending order asc;
select * from book where id%2=1 order by id desc; -- id The query results with cardinality are sorted in descending order
6.3、 Pagination :LIMIT
limit Clause is used to restrict by select The number of data returned by statements , perhaps update,delete The number of operations of the statement , The basic grammar is as follows :
select *
from table_name
where field
limit [num];
-- e.g:
delete from book where price>50 limit 1; -- Delete the first record found
update book set price=20 limit 1; -- The first record price It is amended as follows 20
select * from book where id%2=0 order by id desc limit 1; -- Find the largest even number id
6.4、 The joint query :UNION
UNION Operators are used to connect 2 More than one select The results of a statement are combined into a set of results , Multiple select Statement will delete duplicate data .
UNION Operator syntax format :
select expression1,expression2,...expressionN
from tables
[where conditions]
union [all | distinct]
select expression1,expression2,...expressionN
from tables
[where conditions];
-- explain :
-- all Do not do heavy work , Without or set to distinct Can do the heavy .
-- Different tables can also be queried jointly
Example :
Data in the database :
+----+-------------------+----------------+----------------+-------+
| id | name | type | public | price |
+----+-------------------+----------------+----------------+-------+
| 1 | Long song line | literature , history | Peking University press | 20.00 |
| 2 | Short poetry | literature , history | Peking University press | 52.20 |
| 3 | MySql From entry to abandonment | mathematics | Mechanical industry press | 52.20 |
| 4 | Journey to the west | literature , history , Geography | People's Literature Press | 30.50 |
+----+-------------------+----------------+----------------+-------+
Query statement :
select id,name,type,public,price
from book
where id>2
union all
select id,name,type,public,price
from book
where public=' People's Literature Press ';
Query results :
+----+-------------------+----------------+----------------+-------+
| id | name | type | public | price |
+----+-------------------+----------------+----------------+-------+
| 3 | MySql From entry to abandonment | mathematics | Mechanical industry press | 52.20 |
| 4 | Journey to the west | literature , history , Geography | People's Literature Press | 30.50 |
| 4 | Journey to the west | literature , history , Geography | People's Literature Press | 30.50 |
+----+-------------------+----------------+----------------+-------+
Query statement :
select id,name,type,public,price
from book
where id>2
union distinct
select id,name,type,public,price
from book
where public=' People's Literature Press ';
Query results :
+----+-------------------+----------------+----------------+-------+
| id | name | type | public | price |
+----+-------------------+----------------+----------------+-------+
| 3 | MySql From entry to abandonment | mathematics | Mechanical industry press | 52.20 |
| 4 | Journey to the west | literature , history , Geography | People's Literature Press | 30.50 |
+----+-------------------+----------------+----------------+-------+
6.5、 Group query :GROUP BY
select fieldx Aggregate functions
from Table name
where conditionx
group by fieldx
having conditionx
order by fieldx
limit n;
explain :
- Aggregate functions :avg、max、min、sum、count
- having To further screen the grouped results
Example : stay id>0 The results of , Check the average price of all books in the publishing house , With avg_p Show , Only show that the average price is greater than 35 Result , Reverse order
select public,avg(price) as avg_p
from book
where id>0
group by public
having avg_p>35
order by avg_p desc;
The query results are as follows :
+----------------+-----------+
| public | avg_p |
+----------------+-----------+
| Mechanical industry press | 52.200000 |
| Peking University press | 36.100000 |
+----------------+-----------+
6.6、 nested queries ( Subquery )
Take the query result of the inner layer as the query condition of the outer layer
select ... from Table name where Conditions (select ...);
Example : Check the most expensive books in each publishing house :
select * from book where (public,price) in (select public,max(price) from book group by public);
6.7、 Multi-table query
select table1.field1,table2.field2,...
from table1,table2 where table1.fieldn=table2.fieldn;
6.8、 Link query
Connection query is divided into internal connection 、 Left connection and right connection , The inner connection needs to match the left and right tables at the same time ; The left connection displays the query results mainly in the left table , The right table does not match the display NULL; The right connection displays the query results mainly in the right table , The left table does not match the display NULL;
The format is as follows :
select Field name from surface 1 inner join surface 2 on Conditions inner join surface 3 on Conditions ;
7、 Copy table
When copying a table, the original table will not be copied key attribute , The grammar is as follows :
create table Table name select Query command ;
Example : Copy book Tabular id,name,public,price Field to new table , Take the first three data :
create table copy_book select id,name,public,price from book limit 3;
select * from copy_book;
give the result as follows :
+----+-------------------+----------------+-------+
| id | name | public | price |
+----+-------------------+----------------+-------+
| 1 | Long song line | Peking University press | 20.00 |
| 2 | Short poetry | Peking University press | 52.20 |
| 3 | MySql From entry to abandonment | Mechanical industry press | 52.20 |
+----+-------------------+----------------+-------+
desc see :
desc book;
desc copy_book;
result :

8、 Data backup and recovery
8.1、 Backup
mysqldump -u user name -p Library name > ~/***.sql
Library name surface 1 surface 2 surface 3 Back up multiple tables of the specified library
mysqldump -uroot -p test_book > C:\databk\testbook.sql
-- Backup Library test_book To C:\databk\testbook.sql Next
mysqldump -uroot -p test_book book sale > C:\databk\testbook.sql
-- Backup Library test_book Medium book sale Two tables to C:\databk\testbook.sql Next
8.2、 recovery
mysql -uroot -p Target library name < ***.sql
-- Before recovery, if the database does not exist, you need to build the database first
create database test_book character=utf8;
mysql -uroot -p test_book < C:\databk\testbook.sql
边栏推荐
- ETL tool (data synchronization) II
- Call Gaode map -- address is converted into longitude and latitude
- TS union type
- Promise asynchronous callback function
- 动态内存管理
- serialization and deserialization
- Es5 new method
- Flight control implementation of four rotor aircraft "suggestions collection"
- WebMvcConfigurationSupport
- JS regular expression content:
猜你喜欢

npm+模块加载机制

Why are there many snapshot tables in the BI system?

Source code of wechat applet for discerning flowers and plants / source code of wechat applet for discerning plants

Secure code warrior learning record (III)

@Import

Dynamic memory management

Family relationship calculator wechat applet source code

Npm+ module loading mechanism

chown: changing ownership of ‘/var/lib/mysql/‘: Operation not permitted

Node基础
随机推荐
152. 乘积最大子数组-动态规划
Pytorch data input format requirements and conversion
R language drawing parameters (R language plot drawing)
Query commodity cases (operate data with array addition method) / key points
Moment.js
动态内存管理
[QNX hypervisor 2.2 user manual]9.6 GDB
Strategy mode_
Very simple vsplayaudio online music player plug-in
Npm+ module loading mechanism
Call Gaode map -- address is converted into longitude and latitude
Implementation of mesh parameterized least squares conformal maps (3D mesh mapping to 2D plane)
WordPress removes the website publishing time
Summary of built-in instructions and custom instructions
How does Navicat modify the language (Chinese or English)?
Data broker understanding
CTS test method "suggestions collection"
Solution of phpstudy service environment 80 port occupied by process system under Windows
【MUDUO】EventLoopThreadPool
Enterprise level inventory management system of code audit