1. SQL classification
SQL is the abbreviation of Structured Query Language. It is a standardized language for managing and operating relational database systems. SQL classification is as follows:
- DDL: Data Definition Language, used to define database objects (databases, tables, fields)
- DML: Data manipulation language, used to add, delete, and modify data in database tables
- DQL: Data query language, used to query records in tables in the database
- DCL: Data control language, used to create database users and control database control permissions
2. DDL-data definition language
2.1 DDL-database operations
Query all databases: SHOW DATABASES;
Query current database: SELECT DATABASE();
Create database: CREATE DATABASE [ IF NOT EXISTS ] 数据库名 [ DEFAULT CHARSET 字符集] [COLLATE 排序规则 ];
Delete database: DROP DATABASE [ IF EXISTS ] 数据库名;
Use database: USE 数据库名;
Precautions
- The UTF8 character set is 3 bytes long, and some symbols occupy 4 bytes, so it is recommended to use the utf8mb4 character set.
2.2 DDL-table operations
Query all tables in the current database: SHOW TABLES;
Query table structure: DESC 表名;
Query the table creation statement of the specified table: SHOW CREATE TABLE 表名;
Create table:
CREATE TABLE table name (
field 1 data type constraint,
field 2 data type constraint,
field 3 data type constraint,
...
);
Modify table name: ALTER TABLE 表名 RENAME TO 新表名
Drop table: DROP TABLE [IF EXISTS] 表名;
Drop the table and recreate it: TRUNCATE TABLE 表名;
2.3 DDL-field operations
Add fields: ALTER TABLE 表名 ADD 字段名 类型(长度) [COMMENT 注释] [约束];
Example:ALTER TABLE emp ADD nickname varchar(20) COMMENT '昵称';
Modify field data type: ALTER TABLE 表名 MODIFY 字段名 新数据类型(长度);
Modify field name and field type: ALTER TABLE 表名 CHANGE 旧字段名 新字段名 类型(长度) [COMMENT 注释] [约束];
Example: Modify the nickname field of the emp table to username, and the type is varchar(30) ALTER TABLE emp CHANGE nickname username varchar(30) COMMENT '昵称';
Delete fields: ALTER TABLE 表名 DROP 字段名;
3. Supplement: Data types
3.1 Integer type
type name | Ranges | size |
---|---|---|
TINYINT | -128〜127 | 1 byte |
SMALLINT | -32768〜32767 | 2 bytes |
MEDIUMINT | -8388608〜8388607 | 3 bytes |
INT | -2147483648〜2147483647 | 4 bytes |
BIGINT | -9223372036854775808〜9223372036854775807 | 8 bytes |
Unsigned adds the unsigned keyword after the data type.
3.2 Floating point type
type name | illustrate | storage requirements |
---|---|---|
FLOAT | Single precision floating point number | 4 bytes |
DOUBLE | Double precision floating point number | 8 bytes |
DECIMAL (M, D),DEC | Compressed "strict" fixed-point numbers | M+2 bytes |
3.3 Date and time
type name | date format | date range | storage requirements |
---|---|---|---|
YEAR | YYYY | 1901 ~ 2155 | 1 byte |
TIME | HH:MM:SS | -838:59:59 ~ 838:59:59 | 3 bytes |
DATE | YYYY-MM-DD | 1000-01-01 ~ 9999-12-3 | 3 bytes |
DATETIME | YYYY-MM-DD HH:MM:SS | 1000-01-01 00:00:00 ~ 9999-12-31 23:59:59 | 8 bytes |
TIMESTAMP | YYYY-MM-DD HH:MM:SS | 1980-01-01 00:00:01 UTC ~ 2040-01-19 03:14:07 UTC | 4 bytes |
3.4 String
type name | illustrate | storage requirements |
---|---|---|
CHAR(M) | Fixed length non-binary string (good performance) | M bytes, 1<=M<=255 |
VARCHAR(M) | Variable-length non-binary strings (poor performance) | L+1 bytes, here, L<=M and 1<=M<=255 |
TINYTEXT | very small non-binary string | L+1 bytes, here, L<2^8 |
TEXT | small non-binary string | L+2 bytes, here, L<2^16 |
MEDIUMTEXT | Medium size non-binary string | L+3 bytes, here, L<2^24 |
LONGTEXT | Large non-binary string | L+4 bytes, here, L<2^32 |
ENUM | Enumeration type, can only have one enumeration string value | 1 or 2 bytes, depending on the number of enumeration values (maximum value is 65535) |
SET | A setting, string object can have zero or more SET members | 1, 2, 3, 4, or 8 bytes, depending on the number of set members (maximum 64 members) |
3.5 Binary types
type name | illustrate | storage requirements |
---|---|---|
BIT(M) | Bit field type | About (M+7)/8 bytes |
BINARY(M) | Fixed length binary string | M bytes |
VARBINARY (M) | variable length binary string | M+1 bytes |
TINYBLOB (M) | Very small BLOB | L+1 bytes, here, L<2^8 |
BLOB (M) | small BLOB | L+2 bytes, here, L<2^16 |
MEDIUMBLOB (M) | medium sized BLOB | L+3 bytes, here, L<2^24 |
LONGBLOB (M) | Very large BLOB | L+4 bytes, here, L<2^32 |
4. DML - data manipulation language
4.1 Add data
Specified fields: INSERT INTO 表名 (字段名1, 字段名2, ...) VALUES (值1, 值2, ...);
All fields: INSERT INTO 表名 VALUES (值1, 值2, ...);
Add data in batches: INSERT INTO 表名 (字段名1, 字段名2, ...) VALUES (值1, 值2, ...), (值1, 值2, ...), (值1, 值2, ...);
INSERT INTO 表名 VALUES (值1, 值2, ...), (值1, 值2, ...), (值1, 值2, ...);
Precautions
- String and date type data should be enclosed in quotes
- The size of the inserted data should be within the specified range of the field
4.2 Updating and deleting data
Modify data: UPDATE 表名 SET 字段名1 = 值1, 字段名2 = 值2, ... [ WHERE 条件 ];
Example: UPDATE emp SET name = 'Jack' WHERE id = 1;
delete data: DELETE FROM 表名 [ WHERE 条件 ];
5. DQL - Data Query Language
5.1 Basic query
Query multiple fields: SELECT 字段1, 字段2, 字段3, ... FROM 表名;
SELECT * FROM 表名;
Set alias: SELECT 字段1 [ AS 别名1 ], 字段2 [ AS 别名2 ], 字段3 [ AS 别名3 ], ... FROM 表名;
SELECT 字段1 [ 别名1 ], 字段2 [ 别名2 ], 字段3 [ 别名3 ], ... FROM 表名;
Remove duplicate records: SELECT DISTINCT 字段列表 FROM 表名;
5.2 Conditional query
Condition query: SELECT 字段列表 FROM 表名 WHERE 条件列表;
example:
-- 年龄等于30
select * from employee where age = 30;
-- 年龄小于30
select * from employee where age < 30;
-- 小于等于
select * from employee where age <= 30;
-- 没有身份证
select * from employee where idcard is null or idcard = '';
-- 有身份证
select * from employee where idcard is not null;
-- 不等于
select * from employee where age != 30;
-- 年龄在20到30之间
select * from employee where age between 20 and 30;
select * from employee where age >= 20 and age <= 30;
-- 下面语句不报错,但查不到任何信息
select * from employee where age between 30 and 20;
-- 性别为女且年龄小于30
select * from employee where age < 30 and gender = '女';
-- 年龄等于25或30或35
select * from employee where age = 25 or age = 30 or age = 35;
select * from employee where age in (25, 30, 35);
-- 姓名为两个字
select * from employee where name like '__'; (此处为两个 _ )
-- 身份证最后为X
select * from employee where idcard like '%X';
5.3 Aggregation functions
Grammar: SELECT 聚合函数(字段列表) FROM 表名;
Example: SELECT count(id) from employee where workaddress = "广东省";
5.4 Group query
grammar: SELECT 字段列表 FROM 表名 [ WHERE 条件 ] GROUP BY 分组字段名 [ HAVING 分组后的过滤条件 ];
The difference between where and having:
- The execution timing is different: where is filtering before grouping, and if the where condition is not met, the grouping will not be performed; having is filtering the results after grouping.
- The judgment conditions are different: where cannot judge the aggregate function, but having can.
example:
-- 根据性别分组,统计男性和女性数量(只显示分组数量,不显示哪个是男哪个是女)
select count(*) from employee group by gender;
-- 根据性别分组,统计男性和女性数量
select gender, count(*) from employee group by gender;
-- 根据性别分组,统计男性和女性的平均年龄
select gender, avg(age) from employee group by gender;
-- 年龄小于45,并根据工作地址分组
select workaddress, count(*) from employee where age < 45 group by workaddress;
-- 年龄小于45,并根据工作地址分组,获取员工数量大于等于3的工作地址
select workaddress, count(*) address_count from employee where age < 45 group by workaddress having address_count >= 3;
Precautions
- Execution order: where > aggregate function > having
- After grouping, the fields queried are generally aggregate functions and grouping fields. It is meaningless to query other fields.
5.5 Sorting query
grammar: SELECT 字段列表 FROM 表名 ORDER BY 字段1 排序方式1, 字段2 排序方式2;
sort by:
- ASC: Ascending (default)
- DESC: descending order
example:
-- 根据年龄升序排序
SELECT * FROM employee ORDER BY age ASC;
SELECT * FROM employee ORDER BY age;
-- 两字段排序,根据年龄升序排序,入职时间降序排序
SELECT * FROM employee ORDER BY age ASC, entrydate DESC;
Precautions:
If it is a multi-field sort, only when the first field has the same value, the second field will be sorted.
5.6 分页查询
语法: SELECT 字段列表 FROM 表名 LIMIT 起始索引, 查询记录数;
例子:
-- 查询第一页数据,展示10条
SELECT * FROM employee LIMIT 0, 10;
-- 查询第二页
SELECT * FROM employee LIMIT 10, 10;
注意事项
- 起始索引从0开始,起始索引 = (查询页码 - 1) * 每页显示记录数
- 分页查询是数据库的方言,不同数据库有不同实现,MySQL是LIMIT
- 如果查询的是第一页数据,起始索引可以省略,直接简写 LIMIT 10
六、DQL-执行顺序
DQL执行顺序
FROM -> WHERE -> GROUP BY -> SELECT -> ORDER BY -> LIMIT
七、DCL-数据控制语言 (开发人员操作较少)
7.1 管理用户
查询用户:
USE mysql;
SELECT * FROM user;
创建用户: CREATE USER '用户名'@'主机名' IDENTIFIED BY '密码';
修改用户密码: ALTER USER '用户名'@'主机名' IDENTIFIED WITH mysql_native_password BY '新密码';
删除用户: DROP USER '用户名'@'主机名';
例子:
-- 创建用户test,只能在当前主机localhost访问
create user 'test'@'localhost' identified by '123456';
-- 创建用户test,能在任意主机访问
create user 'test'@'%' identified by '123456';
create user 'test' identified by '123456';
-- 修改密码
alter user 'test'@'localhost' identified with mysql_native_password by '1234';
-- 删除用户
drop user 'test'@'localhost';
注意事项
- 主机名可以使用 % 通配
7.2 权限控制
常用权限:
权限 | 说明 |
---|---|
ALL, ALL PRIVILEGES | 所有权限 |
SELECT | 查询数据 |
INSERT | 插入数据 |
UPDATE | 修改数据 |
DELETE | 删除数据 |
ALTER | 修改表 |
DROP | 删除数据库/表/视图 |
CREATE | 创建数据库/表 |
查询权限: SHOW GRANTS FOR '用户名'@'主机名';
授予权限: GRANT 权限列表 ON 数据库名.表名 TO '用户名'@'主机名';
撤销权限: REVOKE 权限列表 ON 数据库名.表名 FROM '用户名'@'主机名';
注意事项
- 多个权限用逗号分隔
- 授权时,数据库名和表名可以用 * 进行通配,代表所有