对数据的操作
- 插入数据 注意:字符串和日期类型,必须用单引号引起来
语法:insert into 表名 (字段1,字段2,字段3)value(值1,值2,值3);
insert into 表名 values(值1,值2,值3);
-
修改数据
语法:update 表名 set 字段1=值,字段2=值 where 条件;
如果没有where条件语句,默认更新所有的数据
如果有where条件语句,默认更新符合条件的数据
- 删除数据
语法:delete from 表名 where 条件;
如果没有where条件,删除表中所有的数据
1. truncate 表名; --删除表中所有的数据
2. delete from 表名; --删除表中所有的数据
区别:truncate先把整个表删除,然后创建一个空的表(和原来的表结构一样)
delete from 是一行一行的删除(事务可回滚,建议使用此方法)
-
查询数据(重点)
语法:select * from 表名; --查询所有列的记录
select 字段1,字段2,字段3 from 表名; --查询字段1 2 3列的记录
distinct关键字 select distinct 字段1 from 表名; --去除重复的数据
- 查询语句中使用运算和别名 别名关键字as 可以省略
例子: 1. 在所有学生分数上加10分
select name,math+10,(english+10) as e,(chinese+10) c from user;
2. 查询所有学生的总分
select name,(math+english+chinese) 总分 from user;
select s.name,c.id from stu s,class c; ----- 查询stu表的name和class表的id(使用别名,省略as)
- 使用where条件进行过滤
where后面可以使用的运算符
1. > < <= >= = <> 大于、小于、小于等于、大于等于、等于、不等于
2.in表示包含
select * from stu where math in (18,25,66); --查询stu表中,math为18,25,66的数据
3.like 模糊查询 _表示一个字符 %表示多个字符
select * from stu where name like '张_'; --查询name为 ’张‘ 开头的两个字的数据
select * from stu where name like ’张%‘; --查询name为 ’张‘ 开头的记录
4. is null 判断某一个字段记录是否为空
5.and 与 or 或者 not非
- 使用order by对查询的结果排序
语法: select * from 表名 where 条件 order by 列名 升序/降序;
asc 升序 desc 降序 默认是升序 注意:order by子句位于select语句的结尾
- 聚集函数
1.聚集函数:总计某一列数据总和,一列的个数,一列的平均数,一列中最大值,一列中最小值
2.聚集函数来操作列
3. count --计数 sum --求和 avg --平均值
max --最大值 min --最小值 ifnull --判断是否为空,语法:ifnull(XXX,0),如果XXX为null 替换为0
注意:1.sum会把null忽略
练习:统计一个班有多少学生 select count(name) from stu;
统计一个班语文,英语,数学各科的总成绩 select sum(math),sum(english),sum(chinese) from stu;
统计一个班语文成绩平均分,如果有null,就换成0 select avg(ifnull(chinese,0)) from stu;
求班级数学的最高分 select max(math) from stu;
求班级数学的最低分 select min(math) from stu;
- 分组(重要)
关键字 group by
语法:select 列 from 表名 group by 列;
练习:对订单中商品归类后,显示每一类商品的总价 select product,sum(price),count(*) from orders group by product;
查询购买了几类商品,并且每类总价大于100的商品 select product from orders group by product having sum(price) > 100;
总结:having和where都可实现条件过滤,但having条件可以使用聚集函数,where条件不能使用聚集函数,having通常跟在group by 后,它作用与分组
查询总结:select ... from ... where ... group by ... having ... order by ...