当前位置:网站首页>Mysql database - general syntax DDL DML DQL DCL
Mysql database - general syntax DDL DML DQL DCL
2022-06-29 14:31:00 【Super Xiao He】
Catalog
General grammar and classification
DDL( Data definition language )
Table operations - Inquire about
DML( Data operation language )
Aggregate query ( Aggregate functions )
Data model
database A warehouse for storing data , Data is organized and stored DataBase(DB)
Database management system Large software for manipulating and managing databases DataBase Management System(DBMS)
SQL Programming language for operating relational databases , A set of unified standards for operational relational database are defined ,(SQL)

General grammar and classification
Relational database (RDBMS)
Concept :Based on the relational model , A database consisting of multiple interconnected two-dimensional tables .
characteristic :
1. Use tables to store data , use the same pattern , Easy to maintain2. Use sQL Language operation , Unified standards , Easy to use
SQL General grammar
1.SQL Statements can be written in one or more lines , It ends with a semicolon .
2. SQL Statements can use spaces / Indent to enhance the readability of the statement .
3.MySQL Database SQL Statement is case insensitive , It is recommended to use uppercase .
4. notes :
Single-line comments :-- Note content or # The comment (MySQL specific )
Multiline comment :/* The comment */
- DDL: Data definition language , Used to define database objects ( database 、 surface 、 Field )
- DML: Data operation language , It is used to add, delete and modify the data in the database table
- DQL: Data query language , Used to query the records of tables in the database
- DCL: Data control language , Used to create database users 、 Control the control permissions of the database
DDL( Data definition language )
Database operation
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 ;
matters needing attention
- UTF8 The character set length is 3 byte , Some symbols account for 4 byte , So I recommend utf8mb4 Character set
Table operations - Inquire about
Query all tables in the current database :
SHOW TABLES;
Query table structure :
DESC Table name ;
Query the table creation statement of the specified table :
SHOW CREATE TABLE Table name ;
Table operations - establish
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 ];Be careful : There is no comma after the last field
Be careful :[...] Is an optional parameter , There is no comma after the last field
Table operations - modify
Add fields :
ALTER TABLE Table name ADD Field name type ( length ) [COMMENT notes ] [ constraint ];
example :ALTER TABLE emp ADD nickname varchar(20) COMMENT ' nickname ';
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 ];
example : take emp Tabular nickname Change the field to username, The type is varchar(30)ALTER TABLE emp CHANGE nickname username varchar(30) COMMENT ' nickname ';
Table operations - Delete
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 table
Delete table :
DROP TABLE [IF EXISTS] Table name ;
Delete table , And recreate the table :
TRUNCATE TABLE Table name ;
Note when deleting a table , All data in the table will also be deleted
Table operations - data type
DDL- Table operations - data type
MysQL There are many data types in , It is mainly divided into three categories : value type 、 String type 、 Date time type .



An example of adding, deleting, and modifying a query
mysql> use itcast;
Database changed
mysql> create table tb_user(
-> id int comment ' Number ',
-> name varchar(50) comment ' full name ',
-> age int comment ' Age ',
-> gender varchar(1) comment ' Gender '
-> ) comment ' User table ';
Query OK, 0 rows affected (0.03 sec)
mysql> show tables;
+------------------+
| Tables_in_itcast |
+------------------+
| tb_user |
+------------------+
1 row in set (0.00 sec)
mysql> desc tb_user;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id | int | YES | | NULL | |
| name | varchar(50) | YES | | NULL | |
| age | int | YES | | NULL | |
| gender | varchar(1) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
mysql> show create table tb_user;
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| tb_user | CREATE TABLE `tb_user` (
`id` int DEFAULT NULL COMMENT ' Number ',
`name` varchar(50) DEFAULT NULL COMMENT ' full name ',
`age` int DEFAULT NULL COMMENT ' Age ',
`gender` varchar(1) DEFAULT NULL COMMENT ' Gender '
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT=' User table ' |
+---------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)
mysql> create table emp(
-> id int comment ' Number ',
-> workno varchar(10) comment ' Job number ',
-> name varchar(10) comment ' full name ',
-> gender char(1) comment ' Gender ',
-> age tinyint unsigned comment ' Age ',
-> idcard char(18) comment ' ID number ',
-> entrydate date comment ' Entry time '
-> ) comment ' The employee table ';
Query OK, 0 rows affected (0.11 sec)
mysql> desc emp
->
-> desc emp
-> desc emp;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc emp
desc emp' at line 3
mysql> desc emp;
-> desc emp;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc emp' at line 2
mysql>
mysql> create table emp(
-> -> id int comment ' Number ',
-> -> workno varchar(10) comment ' Job number ',
-> -> name varchar(10) comment ' full name ',
-> -> gender char(1) comment ' Gender ',
-> -> age tinyint unsigned comment ' Age ',
-> -> idcard char(18) comment ' ID number ',
-> -> entrydate date comment ' Entry time '
-> -> ) comment ' The employee table ';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-> id int comment ' Number ',
-> workno varchar(10) comment ' Job number ',
-> n' at line 2
mysql>
mysql> desc emp;
+-----------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| id | int | YES | | NULL | |
| workno | varchar(10) | YES | | NULL | |
| name | varchar(10) | YES | | NULL | |
| gender | char(1) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| idcard | char(18) | YES | | NULL | |
| entrydate | date | YES | | NULL | |
+-----------+------------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
mysql> alter table emp add nickname varchar(20) comment ' nickname ';
Query OK, 0 rows affected (0.11 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql>
mysql> desc emp;
+-----------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| id | int | YES | | NULL | |
| workno | varchar(10) | YES | | NULL | |
| name | varchar(10) | YES | | NULL | |
| gender | char(1) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| idcard | char(18) | YES | | NULL | |
| entrydate | date | YES | | NULL | |
| nickname | varchar(20) | YES | | NULL | |
+-----------+------------------+------+-----+---------+-------+
8 rows in set (0.00 sec)
mysql>
mysql> alter table emp change nickname username varchar(30) comment ' user name ';
Query OK, 0 rows affected (0.08 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql>
mysql> desc emp;
+-----------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| id | int | YES | | NULL | |
| workno | varchar(10) | YES | | NULL | |
| name | varchar(10) | YES | | NULL | |
| gender | char(1) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| idcard | char(18) | YES | | NULL | |
| entrydate | date | YES | | NULL | |
| username | varchar(30) | YES | | NULL | |
+-----------+------------------+------+-----+---------+-------+
8 rows in set (0.00 sec)
mysql> alter table emp drop username;
Query OK, 0 rows affected (0.09 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc emp;
+-----------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+------------------+------+-----+---------+-------+
| id | int | YES | | NULL | |
| workno | varchar(10) | YES | | NULL | |
| name | varchar(10) | YES | | NULL | |
| gender | char(1) | YES | | NULL | |
| age | tinyint unsigned | YES | | NULL | |
| idcard | char(18) | YES | | NULL | |
| entrydate | date | YES | | NULL | |
+-----------+------------------+------+-----+---------+-------+
7 rows in set (0.00 sec)
mysql> alter table emp rename to employee;
Query OK, 0 rows affected (0.09 sec)
mysql> desc emp;
ERROR 1146 (42S02): Table 'itcast.emp' doesn't exist
mysql> show table;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
mysql>
mysql> show tables;
+------------------+
| Tables_in_itcast |
+------------------+
| employee |
| tb_user |
+------------------+
2 rows in set (0.00 sec)
mysql>
mysql> drop table if exists tb_user;
Query OK, 0 rows affected (0.09 sec)
mysql> show tables;
+------------------+
| Tables_in_itcast |
+------------------+
| employee |
+------------------+
1 row in set (0.00 sec)
mysql> truncate table employee;
Query OK, 0 rows affected (0.04 sec)
mysql>
mysql> show tables;
+------------------+
| Tables_in_itcast |
+------------------+
| employee |
+------------------+
1 row in set (0.00 sec)
mysql>
Graphical interface tools -DG
DML( Data operation language )
DML Introduce
DML The full English name is Data Manipulation Language( Data operation language ), It is used to record the data of tables in the database Additions and deletions operation .
Add data (INSERT)
Modifying data (UPDATE)Delete data (DELETE)
DML 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, ...);
Be careful :
· When inserting data , The specified field order needs to correspond to the order of values one by one .· String and date data should be enclosed in quotation marks .
· The size of the inserted data , It should be within the specified range of the field .
DML Modifying data
Modifying data :
UPDATE Table name SET Field name 1 = value 1, Field name 2 = value 2, ... [ WHERE Conditions ];
example :UPDATE emp SET name = 'Jack' WHERE id = 1;
DML Delete data
Delete data :
DELETE FROM Table name [ WHERE Conditions ];
DQL( Data query language )
grammar :
SELECTField listFROMTable name fieldWHEREList of conditionsGROUP BYGroup field listHAVINGList of conditions after groupingORDER BYSort field listLIMITPaging parameters
Basic query
Query multiple fields :
SELECT Field 1, Field 2, Field 3, ... FROM Table name ;SELECT * FROM Table name ;
Set alias :
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 ;
escape :
SELECT * FROM Table name WHERE name LIKE '/_ Zhang San ' ESCAPE '/'
/ After that _ Not as a wildcard
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 30
select * from employee where age = 30;
-- Age is less than 30
select * from employee where age < 30;
-- Less than or equal to
select * from employee where age <= 30;
-- 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 != 30;
-- Age 20 To 30 Between
select * from employee where age between 20 and 30;
select * from employee where age >= 20 and age <= 30;
-- The following statement does not report an error , But I can't find any information
select * from employee where age between 30 and 20;
-- 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';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, ";
Group query
grammar :
SELECT Field list FROM Table name [ WHERE Conditions ] GROUP BY Group field name [ HAVING Filter conditions after grouping ];
where and having The difference between :
- 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;matters needing attention
- Execution order :where > Aggregate functions > having
- After grouping , The query fields are generally aggregate functions and grouping fields , Querying other fields makes no sense
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
give an 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;matters needing attention
If it is multi field sorting , When the first field has the same value , Will be sorted according to the second field
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 stripSELECT * FROM employee LIMIT 0, 10;-- Check page twoSELECT * FROM employee LIMIT 10, 10;
- 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
DQL Execution order
FROM -> WHERE -> GROUP BY -> SELECT -> ORDER BY -> LIMIT
DCL( Data control language )
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 ';
-- 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';matters needing attention
- Host name can be used % Pass through
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 |
For more permissions, see List of permissions
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 ';
matters needing attention
- Multiple permissions are separated by commas
- Authorization time , Database name and table name can be * Carry out general matching , On behalf of all
for example :
show grants for 'heima'@'%';
grant all on itcast.* to 'heima'@'%';
revoke all on itcast.* from 'heima'@'%';边栏推荐
- Thanos store component
- 现场快递柜状态采集与控制系统
- 揭秘!付费会员制下的那些小心机!
- [top] blog instructions, bulletin board, message board, about bloggers
- Transport layer user datagram protocol (UDP)
- 【重要通知】中国图象图形学学会2022年度系列奖励推荐工作启动
- 在同花顺上开户安全吗 开户在哪里申请
- go-zero微服务实战系列(七、请求量这么高该如何优化)
- Stable currency risk profile: are usdt and usdc safe?
- Tiktok's global short video dominance may be reversed by YouTube
猜你喜欢

How goby exports scan results
一次mysql的.ibd文件过大处理过程记录

【置顶】博客使用须知,公告板,留言板,关于博主

Investors fell off the altar: 0 sales in half a year, transferred to business and delivered takeout

内网穿透(nc)

数字IC手撕代码--交通灯
![[dark horse morning post] the market value of China public education has evaporated by more than 200billion; New Oriental has more than 20million live fans; HM closes its first store in China; Vanke Y](/img/d7/4671b5a74317a8f87ffd36be2b34e1.jpg)
[dark horse morning post] the market value of China public education has evaporated by more than 200billion; New Oriental has more than 20million live fans; HM closes its first store in China; Vanke Y
![[Jenkins] pipeline controls the sequential execution of multiple jobs for timed continuous integration](/img/04/a650ab76397388bfb62d0dd190dbd0.png)
[Jenkins] pipeline controls the sequential execution of multiple jobs for timed continuous integration

Goby full port scan

【黑马早报】中公教育市值蒸发逾2000亿;新东方直播粉丝破2000万;HM关闭中国首店;万科郁亮称房地产已触底;微信上线“大爆炸”功能...
随机推荐
NuScenes关于Radar的配置信息
Redis主从复制原理
c语言入门教程–-6循环语句
Redis的事务机制
Thinkpad VMware 安装虚拟机出现此主机支持 Intel VT-x,但 Intel VT-x 处于禁用状态(问题解决方法)
《canvas》之第10章 canvas路径
布隆过滤器Bloom Filter简介
【blackduck】jenkins下配置指定的synopsys-detect扫描版本
[QT tutorial] QPushButton key and double click effect
Stable currency risk profile: are usdt and usdc safe?
一次mysql的.ibd文件过大处理过程记录
GWD:基于高斯Wasserstein距离的旋转目标检测 | ICML 2021
By proxy, by buyout, the wild era of domestic end-to-end travel is waiting for the next "eternal robbery"
微信小程序:装B神器P图修改微信流量主小程序源码下载趣味恶搞图制作免服务器域名
systemd调试
[use of veux developer tools - use of getters]
[high concurrency] 28000 words' summary of callable and future interview knowledge points. After reading it, I went directly to ByteDance. Forgive me for being a little drifting (middle)
Characteristics of human immaturity
东莞虎门券商公司股票开户哪个更好更安全?
Turbulent intermediary business, restless renters