当前位置:网站首页>MySQL Basics (concepts, common instructions)
MySQL Basics (concepts, common instructions)
2022-07-25 01:01:00 【Jonny__ Wang】
database
Concept
- database :
An area of a disk dedicated to storing data
- To operate the data in the database, we need to use structured query language (Structured Query Language), namely SQL To achieve
- SQL Is the language that interacts with the database , Be careful ,SQL Not for one DBMS, Almost all DBMS All support SQL, But for different DBMS Come on , They achieve sQL It's not exactly the same
Database management system
A specific software or system that manages databases , Also known as DBMS(DataBase Management System)
Our operation of database , All based on DBMS, Instead of directly manipulating the databasedatabase server
A physical computer , Database installed on it , Specifically used to access data , We can use it remotely DBMS Operate the database
Commonly used instructions
- DDL: Data definition language , be used for Define database objects ( database 、 surface 、 Field )
- DML: Data operation language , It is used to Additions and deletions
- DQL: Data query language , be used for check Query the records of tables in the database
- DCL: Data control language , be used for Create database users 、 Control the control permissions of the database
DDL( Data definition language )
1. Database level
- Query all databases :
SHOW DATABASES; - Querying the current database :
SELECT DATABASE(); - Create database :
CREATE DATABASE [ IF NOT EXISTS ] Database name [ DEFAULT CHARSET Character set ] [COLLATE Sort rule ]; - Delete database :
DROP DATABASE [ IF EXISTS ] Database name ; - Using a database :
USE Database name ;
notes :UTF8 The character set length is 3 byte , Some symbols account for 4 byte , Recommend to use utf8mb4 Character set
2. Surface level
Query all tables in the current database :
SHOW TABLES;Query table structure :
DESC Table name ;Query the table creation statement of the specified table :
mysql SHOW CREATE TABLE Table name ;Create table :
mysql CREATE TABLE Table name ( Field 1 Field 1 type [COMMENT Field 1 notes ], Field 2 Field 2 type [COMMENT Field 2 notes ], Field 3 Field 3 type [COMMENT Field 3 notes ], ... Field n Field n type [COMMENT Field n notes ] )[ COMMENT Table annotation ];Add fields :
ALTER TABLE Table name ADD Field name type ( length ) [COMMENT notes ] [ constraint ];Change data type :
ALTER TABLE Table name MODIFY Field name New data types ( length );Modify the field name and field type :
ALTER TABLE Table name CHANGE Old field name new field name type ( length ) [COMMENT notes ] [ constraint ];Delete field :
ALTER TABLE Table name DROP Field name ;Modify the name of the table :
ALTER TABLE Table name RENAME TO The new name of the tableDelete table :
DROP TABLE [IF EXISTS] Table name ;Delete table , And recreate the table :
TRUNCATE TABLE Table name ;
DML( Data operation language )
1. Add data
Specified field :
INSERT INTO Table name ( Field name 1, Field name 2, ...) VALUES ( value 1, value 2, ...);All fields :
INSERT INTO Table name VALUES ( value 1, value 2, ...);Batch add data :
INSERT INTO Table name ( Field name 1, Field name 2, ...) VALUES ( value 1, value 2, ...), ( value 1, value 2, ...), ( value 1, value 2, ...);INSERT INTO Table name VALUES ( value 1, value 2, ...), ( value 1, value 2, ...), ( value 1, value 2, ...);
notes : String and date type data are enclosed in quotation marks
2. Delete data
- Delete data :
DELETE FROM Table name [ WHERE Conditions ];
3. Change data
- Modifying data :
UPDATE Table name SET Field name 1 = value 1, Field name 2 = value 2, ... [ WHERE Conditions ];
DQL( Data query language )
grammar :
SELECT
Field list
FROM
Table name field
WHERE
List of conditions
GROUP BY
Group field list
HAVING
List of conditions after grouping
ORDER BY
Sort field list
LIMIT
Paging parameters
1. Basic query
Query multiple fields :
SELECT Field 1, Field 2, Field 3, ... FROM Table name ;Query all fields :
SELECT * FROM Table name ;Set alias : Use as keyword ,as Omission
SELECT Field 1 [ AS Alias 1 ], Field 2 [ AS Alias 2 ], Field 3 [ AS Alias 3 ], ... FROM Table name ;SELECT Field 1 [ Alias 1 ], Field 2 [ Alias 2 ], Field 3 [ Alias 3 ], ... FROM Table name ;Remove duplicate records :
SELECT DISTINCT Field list FROM Table name ;
2. Conditions of the query
grammar :
SELECT Field list FROM Table name WHERE List of conditions ;
Conditions :
| Comparison operator | function |
|---|---|
| > | Greater than |
| >= | Greater than or equal to |
| < | Less than |
| <= | Less than or equal to |
| = | be equal to |
| <> or != | It's not equal to |
| BETWEEN … AND … | In a certain range ( Containing minimum 、 Maximum ) |
| IN(…) | stay in The values in the following list , A commonplace |
| LIKE Place holder | Fuzzy matching (_ Match a single character ,% Match any character ) |
| IS NULL | yes NULL |
| Logical operators | function |
|---|---|
| AND or && | also ( Multiple conditions hold at the same time ) |
| OR or || | perhaps ( Any one of several conditions holds ) |
| NOT or ! | Not , No |
give an example :
-- Age equals 50
select * from employee where age = 50;
-- Age is less than 50
select * from employee where age < 50;
-- Less than or equal to 50
select * from employee where age <= 50;
-- No ID card
select * from employee where idcard is null or idcard = '';
-- Have ID card
select * from employee where idcard;
select * from employee where idcard is not null;
-- It's not equal to
select * from employee where age != 50;
-- Age 30 To 50 Between
select * from employee where age between 30 and 50;
select * from employee where age >= 30 and age <= 50;
-- Don't complain , But I can't find any information
select * from employee where age between 50 and 30;
-- The gender is female and the age is less than 30
select * from employee where age < 30 and gender = ' Woman ';
-- Age equals 25 or 30 or 35
select * from employee where age = 25 or age = 30 or age = 35;
select * from employee where age in (25, 30, 35);
-- The name is two words
select * from employee where name like '__';
-- The last ID card is X
select * from employee where idcard like '%X';
3. Aggregate query ( Aggregate functions )
Common aggregate functions :
| function | function |
|---|---|
| count | Statistical quantity |
| max | Maximum |
| min | minimum value |
| avg | Average |
| sum | Sum up |
grammar :
SELECT Aggregate functions ( Field list ) FROM Table name ;
example :SELECT count(id) from employee where workaddress = " Guangdong province, ";
4. Group query
grammar :
SELECT Field list FROM Table name [ WHERE Conditions ] GROUP BY Group field name [ HAVING Filter conditions after grouping ];
where and having difference :
- The timing of execution is different :where Is to filter before grouping , dissatisfaction where Condition does not participate in grouping ;
having Yes, filter the results after grouping . - Different judgment conditions :where Aggregate functions cannot be judged , and having Sure .
Example :
-- Group by sex , Count the number of men and women ( Show only the number of groups , It doesn't show which is male and which is female )
select count(*) from employee group by gender;
-- Group by sex , Count the number of men and women
select gender, count(*) from employee group by gender;
-- Group by sex , Count the average age of men and women
select gender, avg(age) from employee group by gender;
-- Age is less than 45, And grouped according to the working address
select workaddress, count(*) from employee where age < 45 group by workaddress;
-- Age is less than 45, And grouped according to the working address , Get the number of employees greater than or equal to 3 My work address
select workaddress, count(*) address_count from employee where age < 45 group by workaddress having address_count >= 3;
notes :
- Execution order :where > Aggregate functions > having
- After grouping , The query fields are generally aggregate functions and grouping fields , Querying other fields makes no sense
5. Sort query
grammar :SELECT Field list FROM Table name ORDER BY Field 1 sort order 1, Field 2 sort order 2;
sort order :
- ASC: Ascending ( Default )
- DESC: Descending
Example :
-- Sort in ascending order by age
SELECT * FROM employee ORDER BY age ASC;
SELECT * FROM employee ORDER BY age;
-- Two field sorting , Sort in ascending order by age , The entry time is sorted in descending order
SELECT * FROM employee ORDER BY age ASC, entrydate DESC;
notes :
If it is multi field sorting , When the first field has the same value , Will be sorted according to the second field
6. Paging query
grammar :SELECT Field list FROM Table name LIMIT Starting index , Number of query records ;
Example :
-- Query the data on the first page , Exhibition 10 strip
SELECT * FROM employee LIMIT 0, 10;
-- Check page two
SELECT * FROM employee LIMIT 10, 10;
notes :
- Starting index from 0 Start , Starting index = ( Look up the page number - 1) * Each page shows the number of records
- Paging query is the dialect of database , Different databases have different implementations ,MySQL yes LIMIT
- If the query is the first page of data , The starting index can be omitted , Direct abbreviation LIMIT 10
7 DQL Execution order
FROM -> WHERE -> GROUP BY -> SELECT -> ORDER BY -> LIMIT
DCL( Data control language )
1. Manage users
Query the user :
USER mysql;
SELECT * FROM user;
Create user :CREATE USER ' user name '@' Host name ' IDENTIFIED BY ' password ';
Change user password :ALTER USER ' user name '@' Host name ' IDENTIFIED WITH mysql_native_password BY ' New password ';
Delete user :DROP USER ' user name '@' Host name ';
Example :
-- Create user test, Only on the current host localhost visit
create user 'test'@'localhost' identified by '123456';
-- Create user test, Can be accessed from any host
create user 'test'@'%' identified by '123456';
create user 'test' identified by '123456';
-- Change Password
alter user 'test'@'localhost' identified with mysql_native_password by '1234';
-- Delete user
drop user 'test'@'localhost';
notes :
- Host name can be used % Pass through
2. Access control
Common permissions :
| jurisdiction | explain |
|---|---|
| ALL, ALL PRIVILEGES | All permissions |
| SELECT | Query data |
| INSERT | insert data |
| UPDATE | Modifying data |
| DELETE | Delete data |
| ALTER | Modify table |
| DROP | Delete database / surface / View |
| CREATE | Create database / surface |
Query authority :SHOW GRANTS FOR ' user name '@' Host name ';
Grant authority :GRANT Permission list ON Database name . Table name TO ' user name '@' Host name ';
Revoke authority :REVOKE Permission list ON Database name . Table name FROM ' user name '@' Host name ';
notes :
- Multiple permissions are separated by commas
- Authorization time , Database name and table name can be * Carry out general matching , On behalf of all
边栏推荐
- Codeworks round 651 (Div. 2) ABCD solution
- Call camera photo album / upload / scan code in uniapp
- 如何创建索引
- About the difference between for... In and for... Of and object. Keys()
- The IPO of Tuba rabbit was terminated: the annual profit fell by 33%, and Jingwei Sequoia was the shareholder
- [mindspore ascend] [running error] graph_ In mode, run the network to report an error
- On let variable promotion
- Chapter III kernel development
- Latest information of 2022 cloud computing skills competition
- The current situation of the industry is disappointing. After working, I returned to UC Berkeley to study for a doctoral degree
猜你喜欢

Password input box and coupon and custom soft keyboard

Latex notes

7.18 - daily question - 408

C # "learning code snippet" - recursively obtain all files under the folder

The first meta universe auction of Chen Danqing's printmaking works will open tomorrow!

The IPO of Tuba rabbit was terminated: the annual profit fell by 33%, and Jingwei Sequoia was the shareholder

Breederdao's first proposal was released: the constitution of the Dao organization

Moonpdflib Preview PDF usage record

BisinessCardGen

Pursue and kill "wallet Assassin" all over the network
随机推荐
What is iftmcs indicating contract status message?
Pursue and kill "wallet Assassin" all over the network
asp rs.open sql,conn,3,1中3,1代表什么?
[icore4 dual core core _arm] routine 22: LwIP_ UDP experiment Ethernet data transmission
Join MotoGP Monster Energy British Grand Prix!
Redis pipeline technology / partition
Brush questions of binary tree (5)
What is the function of transdata operator and whether it can optimize performance
Vscode installation and configuration
What does it operation and maintenance management mean? How to establish an effective IT operation and maintenance management system?
Esp32 OLED lvgl displays common Chinese characters
About the difference between for... In and for... Of and object. Keys()
Kusionstack open source | exploration and practice of kusion model library and tool chain
Latex notes
Moonpdflib Preview PDF usage record
Game partner topic: the cooperation between breederdao and monkeyleague kicked off
7.14 - daily question - 408
A string "0" was actually the culprit of the collapse of station b
Tiktok iqiyi announced cooperation, long and short video handshake and reconciliation?
#648 (Div. 2)(A. Matrix Game、B. Trouble Sort、C. Rotation Matching)