mysql学习
添加列:
1 | alter table user add column name varchar(20); |
删除列:
1 | alter table user drop column name; |
修改表名:
1 | rename table user to user_user; |
使用中文别名需用双引号
1 | select name as "姓名" from user; |
去除重复数据,null数据也会被去重成一列
1 | select distinct name from user; |
多条字段联合去重
1 | select distinct name,email from user; |
一行注释:
1 | -- 这是注释 |
多行注释
1 | /* |
使用运算表达式
1 | select name, money * 2 as "money2" from user; |
null参与运算结果为null
1 | null + 1, null / 0 |
不依赖表执行运算,得到临时数据
1 | select (1+2)*3 as result; |
不等于的表示
1 | select name from user where money <> 2000; |
日期的比较
1 | select name from user where add_time >= "2000-1-1"; |
where子句使用计算表达式
1 | select name from user where end_money - start_money > 500; |
字符的比较,按字典序,可以得到’2…’,’3…’,不能得到’10…’
1 | select c from user where c > '1'; |
not查询
1 | select name from user where not money > 1000; |
count某个字段
1 | select count(name) from user; |
聚合函数,count(*)除外,自动忽略null
1 | select sum(money) from user; |
sum, avg只能用于数值类型,max, min可以用于任意类型
1 | select max(add_time) from user; |
统计字段不同值的个数
1 | select count(distinct name) from user; |
group by需写在where的后面
执行顺序:from -> where -> group by -> select
没有包含在group by子句中的字段不能写在select、having子句中,可以写在聚合函数中
1 | select class from user group by class having name="xxh"; -- no |
group by执行后结果顺序是随机的
只有select和having、order by子句能使用聚合函数
having子句
1 | select class from user group by class having count(\*)=2; |
能写在where子句中尽量不要写在having子句中,where子句可以针对索引加快执行速度
多个字段的排序,优先使用左侧的add_time字段排序
1 | select name from user order_by add_time, money; |
null值不能参与排序,排序后放在排序结果的末尾
group by子句不能使用别名,order by子句可以
1 | select add_time as a, money as m from user order by a, m; |
sql语句执行顺序: from -> where -> group by -> having -> select -> order by
1 | select name from user order by money; |
插入多行数据
1 | insert into user values('xxh', 18), ('xxh2', 19); |
insert和select联合使用
1 | insert into user_temp(name, age) select name, age from user; |
清空数据表
1 | delete from user; |
update对多字段更新
1 | update user set name='xxh',age=18; |
开启事务
1 | start transaction; |
未提交之前可回滚
1 | start transaction; |
视图保存的是select语句
1 | create view myview (name, age) as select name, age from user; |
多重视图会降低性能,避免使用
1 | create view myview2 (name, avg_age) as select (name, avg(age)) from myview; |
视图的限制:
1、定义视图不能使用order by
2、如果原表可更新(原表创建view时加了where限制也可以通过view插入数据),视图也可以更新,原表若使用了group by则无法更新
子查询原则上都需要使用别名
1 | select * from |
标量子查询,子查询只返回一行数据
1 | -- 查找身高大于平均身高的学生 |
having子句中使用子查询
1 | -- 查处班级平均身高大于全年级平均身高的班级,显示班级和班级平均身高 |
非标量子查询返回多行结果,不能用在=、<>、select子句中
关联子查询,对于子查询返回多行结果的处理方式
1 | -- 取出每个身高大于班级平均身高的学生 |
内置日期函数
1 | select current_date; |
类型转换
1 | select cast('0101' as signed int); |