执行顺序
DCL
函数
字符串函数
数值函数
日期函数
select date_add(now(), INTERVAL 70 DAY);
select datediff('2024-03-05', '2024-02-06');
流程函数
select
name, score,
CASE
WHEN score >45 AND score <=49 THEN 'A'
WHEN score >40 AND score <= 45 THEN 'B'
else 'C'
END as grade
from tb_hotel;
select city,
case city
when '北京' then '一线城市'
when '上海' then '一线城市'
else '二线城市'
end as '工作地址'
from address
约束
create table test_user(
id int PRIMARY KEY auto_increment comment '主键',
name VARCHAR(10) not null unique comment '姓名',
age int comment '年龄' CHECK (age > 0 and age <= 120),
status char(1) DEFAULT '1' comment '状态',
gender char(1) comment '性别'
) comment '用户表';
外键约束
- 添加外键
alter table address add CONSTRAINT fk_address_user_id foreign key (user_id) REFERENCES user(id);
- 删除外键
alter table address drop FOREIGN key fk_address_user_id;
多表查询
内连接
外连接
自连接
select a.name, b.name from emp a , emp b where a.managerid = b.id;
联合查询
- union 和union all
select * from emp where salary >10000
union all
select * from emp where age <50;
返回的字段必须一致, union会做去重处理
子查询
标量子查询
列子查询
行子查询
select * from user where (username, status) = (select username, status from user where name = 'Jack');
表子查询
事务
方式一:
-- 查看事务提交方式
select @@autocommit;
-- 设置事务提交方式 0是手动提交 1自动提交
set @@autocommit=0;
-- 提交事务
COMMIT;
-- 回滚事务
ROLLBACK;
方式二:
- 开启事务
start TRANSACTION;
四大特性ACID
并发事务问题
事务隔离级别
视频
查看事务隔离级别
- 8.0
SELECT @@transaction_isolation;
- 8.0之前
SELECT @@tx_isolation;
设置事务隔离级别
-- 当前会话
set session TRANSACTION ISOLATION LEVEL REPEATABLE READ;
-- 全局
set global TRANSACTION ISOLATION LEVEL REPEATABLE READ;