对表数据的操作
1、【增加数据--insert into】
select * from user:查看表中所有的数据
insert into user(id,name,class,phone)values(1,'zhangsan',1001,'13866666666'):在user表中插
入一条数据
insert into user(id,name,class,phone)values(2,'lisi',1001,13800000000),(3,'wangwu',1002,
13899999999):在user表中插入多条数据
insert into user(name)values('zhaoliu'):在user表中插入一条数据,如果id为自增长,会自动填充
insert into user values(5,'rongqi',1003,15833333333):不写字段名称,直接插入数据,在插入的
数据中所包含的字段数,刚好等于表结构中的字段数,可以直接插入
null:代表空的属性,代表当前的位置对应的存储空间没有被占用,不代表空格,也不是0
手动输入的null代表当前的存储空间,存储的是null这个值
2、【查询数据--select】
select * from user:查询所有数据
select id,name from user:查询指定的字段
select * from user where class = 1001:查询1001班所有的数据
select id,name from user where class =1001:查询1001班的学号和姓名
select phone,name from user:输入的字段顺序就是显示出来的顺序
select * from user where class != 1002:查询不是1002班的所有信息
select phone from user where class = 1001 and name = 'lisi':查询1001班的lisi的电话
select * from user where class = 1001 or class = 1003:查找1001班和1003班的所有信息
select * from user where id > 2 and id < 7:查询3-6行的数据
select * from user where id between 3 and 6:查询3-6行的数据
select * from user where id in (3,4,5,6):查询3-6行的数据
select * from user where id not in (3,5,6):查询除了3,5,6行以外的数据
select * from user limit 2,4:显示3-6行的数据,2代表起始位置的角标,4代表显示的行数
select * from user where class is null:查询不属于任何班级的学生信息
select * from user where name like 'li%':查询user表中姓li的同学,%代表模糊匹配的意思
select * from user where name like '%liu':%放在前面就是模糊匹配前面的内容
select * from user where name like '%gs%':前后都可以模糊匹配
3、【修改数据--update...set】
update user set class = 1002 where class is null:把没有班级信息的人,班级信息修改为1002 班
update user set phone = 18577777777 where phone = 13811111111:修改电话字段
4、【删除数据--】
delete from user where class = 1001:删除1001班的数据
delete from user:删除表中的所有的数据
drop table user:删除表结构
truncate tbuser:快速清空表数据
5、【排序--order by】
select * from user order by id asc:根据id进行升序排序,关键字:asc
select * from user order by id desc:根据id进行降序排序,关键字:desc
select * from user order by id:根据id进行排序,默认为升序排序
6、【分组--group by】
select * from user group by class:根据班级进行分组,显示的每个组别中第一个数据
select class,count(*) from user group by class:group by 一般跟聚合函数连用
select class, count(*) from user group by class having avg(id)>3:查询id平均值大于3 的班级
及其人数,group by 后面接条件的时候不能用where,要用having
1、group by 后面接条件的时候不能用where,要用having
2、使用group by 分组后,仅有分组的字段,和聚合函数,才能放在from之前
3、having后面一般是用身份运算符,或者聚合函数
7、【聚合函数】
count():统计
select count(*) from user:统计user表中的数据量
avg():求平均数
select avg(id) from user:统计user表中id的平均数
sum():求和
select sum(id) from user:求表中id的和
max():最大值
select max(id) from user:求出user表中的最大值
min():最小值
select min(id) from user:求出user表中的最小值
distinct():去重显示
select distinct(phone) from user:将电话号码去重显示
单表查询总结
1.where 不能放在GROUP BY 后面
where 子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,
即在分组之前过滤数据,条件中不能包含聚组函数比如SUM(),AVG()等,使用
where条件显示特定的行。
2.having 是跟GROUP BY 连在一起用的,放在GROUP BY 后面,此时的作用相当
于WHERE。
having 子句的作用是筛选满足条件的组,即在分组之后过滤数据,条件中经常包含
聚组函数,使用having 条件显示特定的组,也可以使用多个分组标准进行分组。
|
|