MySQL基础速览
数据库快忘掉了,回头再总结一下常用语句,还有事务的一些基础知识。
增加
1 | #插入单行 |
删除
1 | #删除满足条件的行 |
修改
1 | #修改 满足条件的行 |
查询
distinct排除重复
1 | select distinct name from teacher; |
between x and y查出x到y范围内的记录
1 | select * from student where score between 60 and 100; |
in查询多个值,或的关系
1 | select * from student where score in(60,70,80); |
or表示或者
1 | select * from student where score = 70 or score = 80; |
order by ... asc/desc升序、降序
1 | select * from student order by age asc; |
count统计和计数
1 | select count(*) from student where score = 60; |
max得出某字段的最大值
1 | select max(score) from student; |
子查询,可以使用括号来嵌入一个子查询
1 | select name,age from student where score = (select max(score) from student); |
limit x,y,从x开始查询y个
1 | select name,age from student order by score desc limit 0,10; |
avg计算平均值
1 | select avg(score) from student where class = 1; |
group by ... having分组
1 | select avg(score) from student group by class; |
like模糊查询
1 | select avg(score) from student group by class having age>16 and name like '王%'; |
多表查询
1 | select cname,sname,score from course,student where course.cid=student.cid; |
year得出时间字段的年份,now得出当前日期和时间
1 | select * from student where year(birthday) = 1998; |
union将两个查询语句的结果合并
1 | select * from class1 union select * from class2; |
as取别名
1 | select sname as name,age from student union all select tname,age from teacher; |
any(子查询语句)表示子查询语句结果的任何一个值
1 | select * from student where age > any(select age from student where name in ('李华', 'Tom')); |
all(子查询语句)表示子查询语句结果的全部值
1 | select * from student where age > all(select age from student where name in ('李华', 'Tom')); |
链接查询
1 | -- 内连接查询 inner join ,inner可省略 ,比如查出有班级的所有学生 |
事务
感受一下什么是事务
1 | -- 关闭mysql的自动提交,不关会自动提交每条sql,rollback无效的 (应用中不需要关,这里是玩 |
begin或start transaction可以开启一个事务
1 | -- 开启事务 begin和start transaction都行 |
事务的四大特征 ACID
1 | A 原子性 |
事务的隔离级别
1 | -- 查看数据库的隔离级别 |
read uncommitted
1 | --修改数据库的隔离级别 为read uncommitted |
就会出现脏读:事务a读到了事务b未commit的数据
read committed
1 | -- 修改数据库的隔离级别 为read committed |
会出现不可重复读:读取同一个表的数据,发现前后不一致
repeatable read可重复读
1 | -- 修改数据库的隔离级别 为repeatable read |
会出现幻读:事务a明明看到表没有变化,但无法插入id为1的行
serializable串行化
1 | -- 修改数据库的隔离级别 为serializable |
性能很差。
隔离与锁有关,隔离级别越高性能越差,未提交读取 > 已提交读取 > 可重复读取 > 串行化
mysql默认为可重复读取