文章目录
- MySQL基础
- 1、SQL语法与分类
- 1.1 DDL 数据定义语言
- 1.1.1 库操作
- 1.1.1.1 查询
- 1.1.1.2 创建
- 1.1.1.3 删除
- 1.1.1.4 使用
- 1.1.2 表+字段操作
- 1.1.2.1 查询
- 1.1.2.2 创建
-
- 1.1.2.3 修改
- 1.1.2.4 删除
- 1.1.3 操作案例
- 1.2 DML 数据操作语言
- 1.2.1 数据操作
- 1.2.1.1 添加 INSERT
- 1.2.1.2 修改 UPDATE
- 1.2.1.3 删除 DELETE
- 1.2.2 操作案例
- 1.3 DQL 数据查询语言
- 1.3.1 查询操作
- 1.3.1.1 基础查询
- 1.3.1.2 条件查询
- 1.3.1.2.1 比较运算符
- 3.1.1.2.2 逻辑运算符
- 1.3.1.3 聚合查询
- 1.3.1.4 分组查询
- 1.3.1.5 排序查询
- 1.3.1.6 分页查询
- 1.3.2 编写顺序与执行顺序的关系
- 1.3.3 操作案例
- 1.3.3.1 创建查询环境
- 1.3.3.2 基础查询
- 1.3.3.3 聚合函数
- 1.3.3.4 排序查询
- 1.3.3.5 分页查询
- 1.4 DCL 数据控制语言
-
- 2、函数
- 2.1 字符串函数
- 2.2 数值函数
- 2.3 日期函数
- 2.4 流程函数
- 3、约束
- 3.1 概述
- 3.2 演示
- 3.3 外键约束
- 3.3.1 父表与子表
- 3.3.2 添加外键
- 3.3.3. 删除外键
- 3.3.4 删除/更新行为
- 4、多表查询
- 4.1 多表关系
- 4.1.1 一对多关系
- 4.1.2 多对多关系
- 4.1.3 一对一关系
- 4.2 多表查询
- 4.2.1 内连接
- 4.2.1.1 隐式内连接
- 4.2.1.2 显式内连接
- 4.2.1.3 操作案例
- 4.2.2 外连接
-
- 4.2.3 自连接
- 4.2.4 联合查询
- 4.2.5 嵌套查询/子查询
- 4.2.5.1 标量子查询
- 4.2.5.2 列子查询
- 4.2.5.3 行子查询
- 4.2.5.4 表子查询
- 5、事务
- 5.1 事务操作
- 5.2 事务特性 - ACID
- 5.3 并发事务问题
- 5.4 事务隔离级别
MySQL基础
MySQL语句不区分大小写
1、SQL语法与分类
- DDL:数据定义语言,定义数据库对象(数据库、表、字段);
- DML:数据操作语言,对数据库表中的数据进行增删改;
- DQL:数据查询语言,查询数据库中表的数据;
- DCL:数据控制语言,创建数据库用户、控制访问权限。
1.1 DDL 数据定义语言
DDL:数据定义语言,定义数据库对象(数据库、表、字段)
1.1.1 库操作
1.1.1.1 查询
SHOW DATABASES;
SELECT DATABASE();
1.1.1.2 创建
CREATE DATABASE [IF NOT EXISTS] 数据库名 [DEFAULT CHARSET 字符集] [COLLATE 排序规则];
1.1.1.3 删除
DROP DATABASE [IF EXISTS] 数据库名;
1.1.1.4 使用
USE 数据库名;
1.1.2 表+字段操作
1.1.2.1 查询
SHOW TABLES;
DESC 表名;
SHOW CREATE TABLE 表名;
1.1.2.2 创建
CREATE TABLE 表名(
字段1 字段1类型 [COMMENT 字段1注释],
字段2 字段2类型 [COMMENT 字段2注释],
字段3 字段3类型 [COMMENT 字段3注释],
...
字段n 字段n类型 [COMMENT 字段n注释]
) [COMMENT 表注释];
数据类型
MySQL中的数据类型很多,主要分为三类:数值类型、字符串类型、日期时间类型。
1.1.2.3 修改
ALTER TABLE 表名 ADD 字段名 类型(长度) [COMMENT 注释] [约束];
ALTER TABLE 表名 MODIFY 字段名 新数据类型(长度);
ALTER TABLE 表名 CHANGE 旧字段名 新字段名 类型(长度) [COMMENT 注释] [约束];
ALTER TABLE 表名 RENAME TO 新表名;
1.1.2.4 删除
DROP TABLE [IF EXISTS] 表名;
TRUNCATE TABLE 表名;
1.1.3 操作案例
mysql> create database test;
Query OK, 1 row affected (0.01 sec)
mysql> use test;
Database changed
mysql> create table aaa(
id int comment 'id',
name varchar(50) comment 'name',
age int comment 'age',
gender varchar(1) comment 'gender'
);
Query OK, 0 rows affected (0.08 sec)
mysql> show tables;
+
| Tables_in_test |
+
| aaa |
+
1 row in set (0.00 sec)
mysql> desc aaa;
+
| 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 aaa;
+
| Table | Create Table |
+
| aaa | CREATE TABLE `aaa` (
`id` int DEFAULT NULL COMMENT 'id',
`name` varchar(50) DEFAULT NULL COMMENT 'name',
`age` int DEFAULT NULL COMMENT 'age',
`gender` varchar(1) DEFAULT NULL COMMENT 'gender'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+
1 row in set (0.00 sec)
mysql> alter table aaa add number int comment 'number';
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc aaa;
+
| Field | Type | Null | Key | Default | Extra |
+
| id | int | YES | | NULL | |
| name | varchar(50) | YES | | NULL | |
| age | int | YES | | NULL | |
| gender | varchar(1) | YES | | NULL | |
| number | int | YES | | NULL | |
+
5 rows in set (0.00 sec)
mysql> alter table aaa modify name varchar(30);
Query OK, 0 rows affected (0.07 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc aaa;
+
| Field | Type | Null | Key | Default | Extra |
+
| id | int | YES | | NULL | |
| name | varchar(30) | YES | | NULL | |
| age | int | YES | | NULL | |
| gender | varchar(1) | YES | | NULL | |
| number | int | YES | | NULL | |
+
5 rows in set (0.00 sec)
mysql> alter table aaa change number numb varchar(10) comment 'change';
Query OK, 0 rows affected (0.05 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc aaa;
+
| Field | Type | Null | Key | Default | Extra |
+
| id | int | YES | | NULL | |
| name | varchar(30) | YES | | NULL | |
| age | int | YES | | NULL | |
| gender | varchar(1) | YES | | NULL | |
| numb | varchar(10) | YES | | NULL | |
+
5 rows in set (0.00 sec)
mysql> alter table aaa rename to bbb;
Query OK, 0 rows affected (0.02 sec)
mysql> show tables;
+
| Tables_in_test |
+
| bbb |
+
1 row in set (0.01 sec)
mysql> drop table if exists bbb;
Query OK, 0 rows affected (0.03 sec)
mysql> show tables;
Empty set (0.00 sec)
1.2 DML 数据操作语言
DML:数据操作语言,对数据库表中的数据进行增删改;
1.2.1 数据操作
1.2.1.1 添加 INSERT
INSERT INTO 表名(字段1名,字段名2,...) VALUES(值1,值2,...);
INSERT INTO 表名 VALUES(值1,值2,...);
INSERT INTO 表名(字段1名,字段名2,...) VALUES(值1,值2,...),(值1,值2,...),;
INSERT INTO 表名 VALUES(值1,值2,...),(值1,值2,...);
1.2.1.2 修改 UPDATE
UPDATE 表名 SET 字段名1=值1,字段名2=值2,... [WHERE 条件];
1.2.1.3 删除 DELETE
DELETE FROM 表名 [WHERE 条件];
1.2.2 操作案例
mysql> create table aaa(
id int comment 'id',
number varchar(10) comment 'number',
name varchar(10) comment 'name',
gender char(1) comment 'gender',
age tinyint unsigned comment 'age',
idcard char(18) comment 'idcard',
date date comment 'date'
);
Query OK, 0 rows affected (0.06 sec)
mysql> show tables;
+
| Tables_in_test |
+
| aaa |
+
1 row in set (0.00 sec)
mysql> insert into aaa values (1,1,'a1','m',18,'111111111111111111','2022-09-15');
Query OK, 1 row affected (0.01 sec)
mysql> select * from aaa;
+
| id | number | name | gender | age | idcard | date |
+
| 1 | 1 | a1 | m | 18 | 111111111111111111 | 2022-09-15 |
+
1 row in set (0.00 sec)
mysql> update aaa set name = 'b1' where id = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from aaa;
+
| id | number | name | gender | age | idcard | date |
+
| 1 | 1 | a1 | m | 18 | 111111111111111111 | 2022-09-15 |
| 2 | 2 | b1 | w | 28 | 111111111111111112 | 2022-09-15 |
+
2 rows in set (0.00 sec)
mysql> update aaa set name = 'a2',gender = 'w' where id = 1;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from aaa;
+
| id | number | name | gender | age | idcard | date |
+
| 1 | 1 | a2 | w | 18 | 111111111111111111 | 2022-09-15 |
| 2 | 2 | b1 | w | 28 | 111111111111111112 | 2022-09-15 |
+
2 rows in set (0.00 sec)
mysql> update aaa set date = '2022-01-01';
Query OK, 2 rows affected (0.01 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> select * from aaa;
+
| id | number | name | gender | age | idcard | date |
+
| 1 | 1 | a2 | w | 18 | 111111111111111111 | 2022-01-01 |
| 2 | 2 | b1 | w | 28 | 111111111111111112 | 2022-01-01 |
+
2 rows in set (0.00 sec)
mysql> update aaa set gender = 'm',date = '2022-01-02';
Query OK, 2 rows affected (0.01 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> select * from aaa;
+
| id | number | name | gender | age | idcard | date |
+
| 1 | 1 | a2 | m | 18 | 111111111111111111 | 2022-01-02 |
| 2 | 2 | b1 | m | 28 | 111111111111111112 | 2022-01-02 |
+
2 rows in set (0.00 sec)
mysql> delete from aaa where name = 'a2';
Query OK, 1 row affected (0.01 sec)
mysql> select * from aaa;
+
| id | number | name | gender | age | idcard | date |
+
| 2 | 2 | b1 | m | 28 | 111111111111111112 | 2022-01-02 |
+
1 row in set (0.00 sec)
1.3 DQL 数据查询语言
DQL:数据查询语言,查询数据库中表的数据;
1.3.1 查询操作
1.3.1.1 基础查询
SELECT 字段1,字段2,... FROM 表名;
SELECT 字段1 [AS 别名1],字段2 [AS 别名2],... FROM 表名;
SELECT DISTINCT 字段列表 FROM 表名;
1.3.1.2 条件查询
SELECT 字段列表 FROM 表名 [WHERE 条件列表];
1.3.1.2.1 比较运算符
>
:大于>=
:大于等于<
:小于<=
:小于等于=
:等于<>或!=
:不等于BETWEEN ... AND ...
:某个范围之间(包含最大值与最小值)IN (...)
:在in之后的列表中的值,多选一LIKE 占位符
:模糊匹配(_
代表多个字符,%
代表任意字符)IS NULL
:是空值
3.1.1.2.2 逻辑运算符
1.3.1.3 聚合查询
将一列数据作为一个整体,进行纵向计算
count
:统计max
:最大值min
:最小值avg
:平均值sum
:求和
SELECT 聚合函数(字段列表) FROM 表名;
1.3.1.4 分组查询
SELECT 字段列表 FROM 表名 [WHERE 条件列表] GROUP BY 分组字段名 [HAVING 分组后过滤条件];
1.3.1.5 排序查询
SELECT 字段列表 FROM 表名 ORDER BY 字段1 排序方式1,字段2 排序方式2;
1.3.1.6 分页查询
SELECT 字段列表 FROM 表名 LIMIT 起始索引,查询记录数;
1.3.2 编写顺序与执行顺序的关系
编号 | 编写顺序 | 执行顺序 |
---|
1 | SELECT | FROM |
2 | FROM | WHERE |
3 | WHERE | GROUP BY |
4 | GROUP BY | HAVING |
5 | HAVING | SELECT |
6 | ORDER BY | ORDER BY |
7 | LIMIT | LIMIT |
1.3.3 操作案例
1.3.3.1 创建查询环境
mysql> insert into aaa values
(1,1,'a1','m',18,'123456789012345678','2022-09-15'),
(2,2,'a2','m',18,'123456789012345678','2021-09-11'),
(3,3,'a3','m',18,'123456789012345678','2022-09-15'),
(4,4,'a4','w',18,'123456783212345678','2012-09-22'),
(5,5,'a5','m',18,'123456782312345678','2021-09-13'),
(6,6,'a6','w',18,'123456789012345678','2020-09-16'),
(7,7,'a7','m',18,'12345674312345678','2021-09-15'),
(8,8,'a8','m',18,'12345678901234567X','2022-09-15'),
(9,9,'a9','w',18,'123452789033345678','2022-09-15'),
(10,10,'b1','m',18,'123456789332345678','2022-03-15'),
(11,11,'b2','w',18,'12345678901445678','2012-02-15'),
(12,12,'b3','m',18,'123455789012345678','2022-09-15'),
(13,13,'b4','w',18,'null','2022-09-15'),
(14,14,'b5','m',18,'12345678901234567X','2012-09-15');
Query OK, 14 rows affected (0.01 sec)
1.3.3.2 基础查询
mysql> select id from aaa;
+
| id |
+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
| 11 |
| 12 |
| 13 |
| 14 |
+
14 rows in set (0.00 sec)
mysql> select id,name from aaa;
+
| id | name |
+
| 1 | a1 |
| 2 | a2 |
| 3 | a3 |
| 4 | a4 |
| 5 | a5 |
| 6 | a6 |
| 7 | a7 |
| 8 | a8 |
| 9 | a9 |
| 10 | b1 |
| 11 | b2 |
| 12 | b3 |
| 13 | b4 |
| 14 | b5 |
+
14 rows in set (0.00 sec)
mysql> select * from aaa;
+
| id | number | name | gender | age | idcard | date |
+
| 1 | 1 | a1 | m | 18 | 123456789012345678 | 2022-09-15 |
| 2 | 2 | a2 | m | 18 | 123456789012345678 | 2021-09-11 |
| 3 | 3 | a3 | m | 18 | 123456789012345678 | 2022-09-15 |
| 4 | 4 | a4 | w | 18 | 123456783212345678 | 2012-09-22 |
| 5 | 5 | a5 | m | 18 | 123456782312345678 | 2021-09-13 |
| 6 | 6 | a6 | w | 18 | 123456789012345678 | 2020-09-16 |
| 7 | 7 | a7 | m | 18 | 12345674312345678 | 2021-09-15 |
| 8 | 8 | a8 | m | 18 | 12345678901234567X | 2022-09-15 |
| 9 | 9 | a9 | w | 18 | 123452789033345678 | 2022-09-15 |
| 10 | 10 | b1 | m | 18 | 123456789332345678 | 2022-03-15 |
| 11 | 11 | b2 | w | 18 | 12345678901445678 | 2012-02-15 |
| 12 | 12 | b3 | m | 18 | 123455789012345678 | 2022-09-15 |
| 13 | 13 | b4 | w | 18 | null | 2022-09-15 |
| 14 | 14 | b5 | m | 18 | 12345678901234567X | 2012-09-15 |
+
14 rows in set (0.00 sec)
mysql> select id as id_alias from aaa;
+
| id_alias |
+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
| 11 |
| 12 |
| 13 |
| 14 |
+
14 rows in set (0.01 sec)
mysql> select id as id_alias,name name_alias from aaa;
+
| id_alias | name_alias |
+
| 1 | a1 |
| 2 | a2 |
| 3 | a3 |
| 4 | a4 |
| 5 | a5 |
| 6 | a6 |
| 7 | a7 |
| 8 | a8 |
| 9 | a9 |
| 10 | b1 |
| 11 | b2 |
| 12 | b3 |
| 13 | b4 |
| 14 | b5 |
+
14 rows in set (0.00 sec)
mysql> select distinct * from aaa;
1.3.3.3 聚合函数
mysql> select count(*) from aaa group by gender;
+
| count(*) |
+
| 9 |
| 5 |
+
2 rows in set (0.00 sec)
mysql> select gender,count(*) from aaa group by gender;
+
| gender | count(*) |
+
| m | 9 |
| w | 5 |
+
2 rows in set (0.00 sec)
mysql> select name,gender,count(*) from aaa group by gender;
ERROR 1055 (42000): Expression
mysql> select gender,avg(age) from aaa group by gender;
+
| gender | avg(age) |
+
| m | 18.0000 |
| w | 18.0000 |
+
2 rows in set (0.00 sec)
mysql> select gender,count(*) gender_num from aaa where id > 5 group by gender having gender_num <= 4;
+
| gender | gender_num |
+
| w | 4 |
+
1 row in set (0.00 sec)
1.3.3.4 排序查询
mysql> select number from aaa order by number desc;
+
| number |
+
| 9 |
| 8 |
| 7 |
| 6 |
| 5 |
| 4 |
| 3 |
| 2 |
| 14 |
| 13 |
| 12 |
| 11 |
| 10 |
| 1 |
+
14 rows in set (0.00 sec)
1.3.3.5 分页查询
mysql> select id from aaa limit 10;
+
| id |
+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
+
10 rows in set (0.00 sec)
mysql> select id from aaa limit 10,10;
+
| id |
+
| 11 |
| 12 |
| 13 |
| 14 |
+
4 rows in set (0.00 sec)
1.4 DCL 数据控制语言
DCL:数据控制语言,创建数据库用户、控制访问权限。
1.4.1 控制操作
1.4.1.1 管理用户
USE mysql;
SELECT * FROM user;
CREATE USER '用户名'@'主机名' IDENTIFIED BY '密码';
ALTER USER '用户名'@'主机名' IDENTIFIED WITH mysql_native_password BY '新密码';
DROP USER '用户名'@'主机名';
1.4.1.2 权限控制
SHOW GRANTS FOR '用户名'@'主机名';
GRANT 权限列表 ON 数据库名.表名 TO '用户名'@'主机名';
REVOKE 权限列表 ON 数据库名.表名 FROM '用户名'@'主机名';
权限类型
ALL/ALL PRIVILEGES
:所有权限;SELECT
:查询数据INSERT
:插入数据;UPDATE
:修改数据DELETE
:删除数据;ALTER
:修改表;DROP
:删除数据库/表/视图;CREATE
:创建数据库/表。
1.4.2 操作案例
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select user,host from user;
+
| user | host |
+
| root | % |
| mysql.infoschema | localhost |
| mysql.session | localhost |
| mysql.sys | localhost |
| root | localhost |
+
5 rows in set (0.00 sec)
mysql> create user 'test'@'localhost' identified by '123456';
Query OK, 0 rows affected (0.02 sec)
mysql> select * from user where user = 'test'\G;
*************************** 1. row ***************************
Host: localhost
User: test
Select_priv: N
Insert_priv: N
Update_priv: N
Delete_priv: N
Create_priv: N
Drop_priv: N
Reload_priv: N
Shutdown_priv: N
Process_priv: N
File_priv: N
Grant_priv: N
References_priv: N
Index_priv: N
Alter_priv: N
Show_db_priv: N
Super_priv: N
Create_tmp_table_priv: N
Lock_tables_priv: N
Execute_priv: N
Repl_slave_priv: N
Repl_client_priv: N
Create_view_priv: N
Show_view_priv: N
Create_routine_priv: N
Alter_routine_priv: N
Create_user_priv: N
Event_priv: N
Trigger_priv: N
Create_tablespace_priv: N
ssl_type:
ssl_cipher: 0x
x509_issuer: 0x
x509_subject: 0x
max_questions: 0
max_updates: 0
max_connections: 0
max_user_connections: 0
plugin: caching_sha2_password
authentication_string: $A$005$@>
]e@](nWSAXZLmMlse0qcw8nocN0xwJPLXw2YKvELqgcoISHqFTI1
password_expired: N
password_last_changed: 2022-09-16 07:39:12
password_lifetime: NULL
account_locked: N
Create_role_priv: N
Drop_role_priv: N
Password_reuse_history: NULL
Password_reuse_time: NULL
Password_require_current: NULL
User_attributes: NULL
1 row in set (0.00 sec)
ERROR:
No query specified
开启第二窗口,使用新账户登录MySQL数据库
sh-4.4
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 15
Server version: 8.0.30 MySQL Community Server - GPL
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+
| Database |
+
| information_schema |
| performance_schema |
+
2 rows in set (0.00 sec)
mysql> alter user 'test'@'localhost' identified with mysql_native_password by '1234';
Query OK, 0 rows affected (0.01 sec)
sh-4.4
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 18
Server version: 8.0.30 MySQL Community Server - GPL
Copyright (c) 2000, 2022, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
mysql> show grants for 'test'@'localhost';
+
| Grants for test@localhost |
+
| GRANT USAGE ON *.* TO `test`@`localhost` |
+
1 row in set (0.00 sec)
mysql> grant all on test.* to 'test'@'localhost';
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> show grants for 'test'@'localhost';
+
| Grants for test@localhost |
+
| GRANT USAGE ON *.* TO `test`@`localhost` |
| GRANT ALL PRIVILEGES ON `test`.* TO `test`@`localhost` |
+
2 rows in set (0.00 sec)
mysql> show databases;
+
| Database |
+
| information_schema |
| performance_schema |
| test |
+
3 rows in set (0.00 sec)
2、函数
函数的使用方法:
SELECT 函数(参数);
2.1 字符串函数
函数 | 功能 |
---|
CONCAT(S1,S2,...Sn) | 字符串拼接,将S1,S2...Sn 拼接成一个字符串 |
LOWER(str) | 将字符串转全部为小写 |
UPPER(str) | 将字符串全部转为大写 |
LPAD(str,n,pad) | 左填充,用字符串pad 填充str 左边达到n 个单位长度 |
RPAD(str,n,pad) | 右填充,用字符串pad 填充str 右边达到n 个单位长度 |
TRIM(str) | 去掉字符串头部和尾部的空格 |
SUBSTRING(str, start,len) | 返回从字符串str 从start 位置起始的len 个长度字符串,索引从1开始 |
mysql> select concat('Hello','World','!');
+
| concat('Hello','World','!') |
+
| HelloWorld! |
+
1 row in set (0.00 sec)
mysql> select lower('HELLO WORLD');
+
| lower('HELLO WORLD') |
+
| hello world |
+
1 row in set (0.00 sec)
mysql> select upper('hello world');
+
| upper('hello world') |
+
| HELLO WORLD |
+
1 row in set (0.00 sec)
mysql> select lpad('Hello',7,'$');
+
| lpad('Hello',7,'$') |
+
| $$Hello |
+
1 row in set (0.00 sec)
mysql> select rpad('Hello',7,'$');
+
| rpad('Hello',7,'$') |
+
| Hello$$ |
+
1 row in set (0.01 sec)
mysql> select trim(' Hello Wor ld ');
+
| trim(' Hello Wor ld ') |
+
| Hello Wor ld |
+
1 row in set (0.00 sec)
mysql> select substring('Hello World',7,3);
+
| substring('Hello World',7,3) |
+
| Wor |
+
1 row in set (0.00 sec)
2.2 数值函数
函数 | 功能 |
---|
CEIL(x) | 向上取整 |
FLOOR(x) | 向下取整 |
MOD(x,y) | 返回x/y 的模 |
RAND() | 返回0-1 内的随机数 |
ROUND(x,y) | 求参数x 的四舍五入值,并保留y 位小数 |
mysql> select ceil(3.2);
+
| ceil(3.2) |
+
| 4 |
+
1 row in set (0.00 sec)
mysql> select floor(3.2);
+
| floor(3.2) |
+
| 3 |
+
1 row in set (0.00 sec)
mysql> select mod(3,2);
+
| mod(3,2) |
+
| 1 |
+
1 row in set (0.00 sec)
mysql> select rand();
+
| rand() |
+
| 0.1530892738635552 |
+
1 row in set (0.00 sec)
mysql> select round(rand(),5);
+
| round(rand(),5) |
+
| 0.34433 |
+
1 row in set (0.00 sec)
2.3 日期函数
函数 | 功能 |
---|
CURDATE() | 返回当前日期 |
CURTIME() | 返回当前时间 |
NOW() | 返回当前日期和时间 |
YEAR(date) | 获取指定date 的年 |
MONTH(date) | 获取指定date 的月 |
DAY(date) | 获取指定date 的日 |
DATE_ADD(date,INTERVAL express type) | 返回上一个日期/时间值加上一个时间间隔expr 后的时间值 |
DATEDIFF(date1,date2) | 返回date1 与date2 之间的天数 |
mysql> select curdate();
+
| curdate() |
+
| 2022-09-20 |
+
1 row in set (0.00 sec)
mysql> select year(curdate());
+
| year(curdate()) |
+
| 2022 |
+
1 row in set (0.00 sec)
mysql> select date_add(curdate(),interval 10 year);
+
| date_add(curdate(),interval 10 year) |
+
| 2032-09-20 |
+
1 row in set (0.00 sec)
2.4 流程函数
函数 | 功能 |
---|
IF(value,t,f) | 如果value 为true ,返回t ,否则返回f |
IFNULL(value1,value2) | 如果value1 不为空,返回value1 ,否则返回value2 (只要不为null ,就返回value1 ,包含'' ) |
CASE WHEN [val1] THEN [res1] ... ELSE [default] END | 如果val1 为true,返回res1,… 否则返回default |
CASE [expr] WHEN [val1] THEN [res1] ... ELSE [default] END | 如果expr 的值等于val1 ,返回res1 ,… 否则返回default |
mysql> select if(true,'ok','no');
+
| if(true,'ok','no') |
+
| ok |
+
1 row in set (0.00 sec)
mysql> select if(false,'ok','no');
+
| if(false,'ok','no') |
+
| no |
+
1 row in set (0.00 sec)
mysql> select ifnull('','bbb');
+
| ifnull('','bbb') |
+
| |
+
1 row in set (0.00 sec)
mysql> select ifnull(null,'bbb');
+
| ifnull(null,'bbb') |
+
| bbb |
+
1 row in set (0.00 sec)
mysql> select name,(case gender when 'w' then 'woman' else 'man' end) as xingbie from aaa;
+
| name | xingbie |
+
| a1 | man |
| a2 | man |
| a3 | man |
| a4 | woman |
| a5 | man |
| a6 | woman |
| a7 | man |
| a8 | man |
| a9 | woman |
| b1 | man |
| b2 | woman |
| b3 | man |
| b4 | woman |
| b5 | man |
+
14 rows in set (0.00 sec)
3、约束
3.1 概述
概念:约束是作用于表中字段上的规则,用于限制存储在表中的数据。
目的:保证数据库中数据的正确、有效性和完整性。
约束 | 描述 | 关键字 |
---|
非空约束 | 限制该字段的数据不能为NULL | NOT NULL |
唯一约束 | 保证该字段的所有数据都是唯一、不重复的 | UNIQUE |
主键约束 | 主键是一行数据的唯一标识,要求非空且唯一 | PRIMARY KEY |
默认约束 | 保存数据时,如果未指定该字段的值,则采用默认值 | DEFAULT |
检查约束(8.0.16版本之后) | 保证字段值满足某个条件 | CHECK |
外键约束 | 用来让两张表的数据之间建立连接,保证数据一致性与完整性 | FOREIGN KEY |
约束是作用于表中字段上的,可以在创建表/修改表的时候添加约束
3.2 演示
mysql> create table user(
id int auto_increment primary key comment '标识',
name varchar(10) not null unique comment '姓名',
age int check(age>0 && age<=120) comment '年龄',
status char(1) default '1' comment '状态',
gender char(1) comment '性别'
);
3.3 外键约束
外键用来让两张表的数据之间建立连接,从而保证数据的一致性与完整性。
3.3.1 父表与子表
父表:关联表的目标字段所在的表;
子表:关联表的起始字段所在的表。
3.3.2 添加外键
CREATE TABLE 表名(
字段名 数据类型;
...
[CONSTRAINT] [外键名称] FOREIGN KEY (外键字段名) REFERENCES 主表 (主表列名)
);
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名) REFERENCES 主表 (主表列名);
3.3.3. 删除外键
ALTER TABLE 表名 DROP FOREIGN KEY (外键名称);
3.3.4 删除/更新行为
关键字 | 功能 |
---|
NO ACTION | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新(与RESTRICT 一致) |
RESTRICT | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不允许删除/更新(与NO ACTION 一致) |
CASCADE | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则也删除/更新外键在子表中的记录 |
SET NULL | 当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则设置子表中该外键值为NULL (要求外键允许NULL ) |
SET DEFAULT | 当在父表中删除/更新对应记录时,子表将外键列设置成一个默认的值 |
语法结构:
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名) REFERENCES 主表名 (主表列名) ON UPDATE CASCADE ON DELETE CASCADE
4、多表查询
4.1 多表关系
项目开发中,在进行数据库表名结构设计时,会根据业务需求及业务模块之间的关系,分析并设计表结构,由于业务之间相互关联,所以各个表结构之间也存在着各种联系,基本上分为三种:
4.1.1 一对多关系
案例:一个部门可以对应多个员工,一个员工对应一个部门
实现方式:在多对一方建立外键,指向一的一方的主键
4.1.2 多对多关系
案例:一个学生可以选择多门课程,一门课程也可以被多个学生选择
实现方式:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键
4.1.3 一对一关系
案例:一对一关系多用于单表拆分,将一张表的基础字段放在一张表中,其他详细字段放在另一张表中,以提升操作效率
实现方式:在任意一方加入外键,关联另外一方的主键,并且设置外键为唯一UNIQUE
4.2 多表查询
多表查询:从多张表中查询数据。
笛卡尔积:笛卡尔积指在数学中,两个集合A和B的所有组合情况,在多表查询中,需要消除无效的笛卡尔积。
多表查询分类:
- 连接查询
- 内连接:查询A、B交集部分的数据;
- 外连接
- 左外连接:查询左表所有数据+交集数据;
- 右外连接:查询右表所有数据+交集数据;
- 子查询
4.2.1 内连接
内连接分为隐式内连接与显式内连接两种。
4.2.1.1 隐式内连接
SELECT 字段列表 FROM 表1,表2 WHERE 条件 ...;
4.2.1.2 显式内连接
SELECT 字段列表 FROM 表1 [INNER] JOIN 表2 ON 连接条件 ...;
4.2.1.3 操作案例
mysql> create table user(
id int comment '标识',
name varchar(10) comment '姓名',
age int comment '年龄',
status char(1) comment '状态',
user_id int comment '部门id',
gender char(1) comment '性别'
);
mysql> create table dept(
id int comment '标识',
name varchar(20) comment '部门'
);
mysql> insert into user values
(1,'aaa',81,'i',4,'m'),
(2,'bbb',27,'i',1,'w'),
(3,'ccc',33,'i',2,'m'),
(4,'ddd',21,'i',2,'w'),
(5,'eee',48,'i',3,'w'),
(6,'fff',69,'i',3,'m'),
(7,'ggg',22,'i',2,'m')
;
mysql> insert into dept values
(1,'yanfa'),
(2,'xiaoshou'),
(3,'shouqian'),
(4,'CEO')
;
mysql> select * from user;
+
| id | name | age | status | user_id | gender |
+
| 1 | aaa | 81 | i | 4 | m |
| 2 | bbb | 27 | i | 1 | w |
| 3 | ccc | 33 | i | 2 | m |
| 4 | ddd | 21 | i | 2 | w |
| 5 | eee | 48 | i | 3 | w |
| 6 | fff | 69 | i | 3 | m |
| 7 | ggg | 22 | i | 2 | m |
+
7 rows in set (0.00 sec)
mysql> select * from dept;
+
| id | name |
+
| 1 | yanfa |
| 2 | xiaoshou |
| 3 | shouqian |
| 4 | CEO |
+
4 rows in set (0.00 sec)
ALTER TABLE 表名 ADD CONSTRAINT 外键名称 FOREIGN KEY (外键字段名) REFERENCES 主表名 (主表列名) ON UPDATE CASCADE ON DELETE CASCADE
4.2.2 外连接
4.2.2.1 左外连接
相当于查询表1的所有数据包含表1与表2的交集数据。
SELECT 字段列表 FROM 表1 LEFT [OUTER] JOIN 表2 ON 条件 ...;
4.2.2.2 右外连接
相当于查询表2的所有数据包含表1与表2的交集数据。
SELECT 字段列表 FROM 表1 RIGHT [OUTER] JOIN 表2 ON 条件 ...;
4.2.3 自连接
自连接查询可以是内连接查询,也可以是外连接查询。
SELECT 字段列表 FROM 表1 别名1 JOIN 表1 别名2 ON 条件 ...;
4.2.4 联合查询
对于union查询,就是把多次查询的结果合并形成一个新的查询结果集合。
SELECT 字段列表 FROM 表1 ...
UNION [ALL]
SELECT 字段列表 FROM 表2 ...;
4.2.5 嵌套查询/子查询
SQL语句中嵌套SELECT语句,成为嵌套查询,又称为子查询。
SELECT * FROM 表1 WHERE 条件1=(SELECT 字段名称 FROM 表2);
根据子查询结果不同可以分为:
- 标量子查询:查询结果为单个值;
- 列子查询:查询结果为列;
- 行子查询
- 表子查询
根据子查询位置可以分为:
4.2.5.1 标量子查询
mysql> select id from dept where name = 'yanfa';
+
| id |
+
| 1 |
+
1 row in set (0.00 sec)
mysql> select * from user where user_id = 1;
+
| id | name | age | status | user_id | gender |
+
| 2 | bbb | 27 | i | 1 | w |
+
1 row in set (0.00 sec)
mysql> select * from user where user_id = (select id from dept where name = 'yanfa');
+
| id | name | age | status | user_id | gender |
+
| 2 | bbb | 27 | i | 1 | w |
+
1 row in set (0.00 sec)
4.2.5.2 列子查询
常用操作符 | 功能 |
---|
IN | 指定范围内多选一 |
NOT IN | 不在指定范围内 |
ANY | 子查询返回列表中满足一个即可 |
SOME | 与ANY 相同 |
ALL | 子查询返回列表中所有值全部满足 |
mysql> select id from dept where name = 'yanfa' or name = 'xiaoshou';
mysql> select * from user where user_id = 1 or user_id = 2;
mysql> select * from user where user_id in (select id from dept where name = 'yanfa' or name = 'xiaoshou');
+
| id | name | age | status | user_id | gender |
+
| 2 | bbb | 27 | i | 1 | w |
| 3 | ccc | 33 | i | 2 | m |
| 4 | ddd | 21 | i | 2 | w |
| 7 | ggg | 22 | i | 2 | m |
+
4 rows in set (0.00 sec)
mysql> select id from dept where name = 'xiaoshou';
mysql> select age from user where user_id = (select id from dept where name = 'xiaoshou');
+
| age |
+
| 33 |
| 21 |
| 22 |
+
3 rows in set (0.00 sec)
mysql> select * from user where age > all(select age from user where user_id = (select id from dept where name = 'xiaoshou'));
+
| id | name | age | status | user_id | gender |
+
| 1 | aaa | 81 | i | 4 | m |
| 5 | eee | 48 | i | 3 | w |
| 6 | fff | 69 | i | 3 | m |
+
3 rows in set (0.00 sec)
mysql> select * from user where age > any(select age from user where user_id = (select id from dept where name = 'xiaoshou'));
+
| id | name | age | status | user_id | gender |
+
| 1 | aaa | 81 | i | 4 | m |
| 2 | bbb | 27 | i | 1 | w |
| 3 | ccc | 33 | i | 2 | m |
| 5 | eee | 48 | i | 3 | w |
| 6 | fff | 69 | i | 3 | m |
| 7 | ggg | 22 | i | 2 | m |
+
6 rows in set (0.00 sec)
4.2.5.3 行子查询
常用操作符:=
、<>
、IN
、NOT IN
。
mysql> select user_id,gender from user where name='ccc';
+
| user_id | gender |
+
| 2 | m |
+
1 row in set (0.00 sec)
mysql> select * from user where (user_id,gender) = (2,'m');
+
| id | name | age | status | user_id | gender |
+
| 3 | ccc | 33 | i | 2 | m |
| 7 | ggg | 22 | i | 2 | m |
+
2 rows in set (0.00 sec)
mysql> select * from user where (user_id,gender) = (select user_id,gender from user where name='ccc');
+
| id | name | age | status | user_id | gender |
+
| 3 | ccc | 33 | i | 2 | m |
| 7 | ggg | 22 | i | 2 | m |
+
2 rows in set (0.00 sec)
4.2.5.4 表子查询
常用操作符:IN
。
mysql> select user_id,gender from user where name='ccc' or name = 'ddd';
+
| user_id | gender |
+
| 2 | m |
| 2 | w |
+
2 rows in set (0.00 sec)
mysql> select * from user where (user_id,gender) in (select user_id,gender from user where name='ccc' or name = 'ddd');
+
| id | name | age | status | user_id | gender |
+
| 3 | ccc | 33 | i | 2 | m |
| 4 | ddd | 21 | i | 2 | w |
| 7 | ggg | 22 | i | 2 | m |
+
3 rows in set (0.00 sec)
5、事务
事务是一组操作的集合,它是一个不可分割的工作单位,事务会把所有的操作作为一个整体一起向系统提交或撤销操作请求,即这些操作要么同时成功,要么同时失败。
5.1 事务操作
默认MySQL得事务是自动提交的,当执行一条DML语句时,会立即隐式提交事务。
mysql> select @@autocommit;
+
| @@autocommit |
+
| 1 |
+
1 row in set (0.00 sec)
mysql> set @@autocommit = 0;
mysql> start transaction;
mysql> begin;
mysql> commit;
mysql> rollback;
5.2 事务特性 - ACID
- 原子性(Atomicity):事务是不可分割的最小操作单元,要么全部成功,要么全部失败;
- 一致性(Consistency):事务完成时,必须使所有数据都保持一致状态;
- 隔离性(Isolation):数据库系统提供的隔离机制,保证事务在不受外部并发操作影响的独立环境下运行;
- 持久性(Durability):事务一旦提交或回滚,对数据库的改变是永久的。
5.3 并发事务问题
- 脏读:一个事物读到另一个事务还没有提交的数据;
- 不可重复读:一个事务先后读取同一条记录,但是两次读取的数据不同;
- 幻读:一个事务按照条件查询数据时,没有对应的数据行,但是在插入数据时,又发现这行数据已经存在,出现了幻影。
5.4 事务隔离级别
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)