MySQL基础教程下篇 (修改查询)

数据的修改查询

原始数据:

修改数据:

update 表名称 set 字段名=修改值 [,字段名=修改值,...] [where 条件];

1. 将所有学生的成绩改为60

update student set score=60;

2. 将id为10的学生的成绩修改为100

update student set score=100 where id=10;

3. 将id大于10的学生,年龄增加2岁,成绩提高5分

update student set age=age+2,score=score+5 where id>6;

4. 删除记录

1. 删除所有成绩不及格的学生

delete from student where score<60;

5.查询记录

1. 查询所有学生的所有字段

select * from student;

2. 查询所有学生的姓名和成绩

select name,score from student;

3. 查询所有学生的姓名和成绩,并将查询字段的别名改为汉字

select name as 姓名,score as 成绩 from student;

4. 查询成绩大于80分的学生姓名与成绩

select name,score from student where score>80;

限制查询:

查询限定条数:select 字段列表 from 表名称 [where 条件] limit 最多记录数;

从指定偏移量查询限定条数:select 字段列表 from 表名称 [where 条件] limit 偏移量,最多记录数;

1.查询student表中的前3条记录

select * from student limit 3;

2.查询student表中的第3~第5条记录(从偏移量为2开始查,最多查3条)

select * from student limit 2,4;

排序查询:

select 字段列表 from 表名称 [where 条件] order by 字段名[desc] [,字段名...];

1. 按照成绩升序排序

select * from student order by score;

2. 按照成绩降序排序

select * from student order by score desc;

3. 先按照成绩降序排序,如果成绩相等,则再按照年龄升序排序

select * from student order by score desc,age;

4. 查询成绩是前三名的学生记录

select * from student order by score desc limit 3;

分组查询:

select 字段列表 from 表名称 [where 条件] group by 分组字段列表 [having 对分组后的筛选条件];

注:分组查询经常与聚合函数一起使用

注:分组字段应该与查询字段保持一致

1. 创建产品表

create table product(

id int primary key auto_increment,

name varchar(20) not null,

price double not null,

address varchar(20),

type varchar(20)

);

2. 插入记录

insert into product(name,price,address,type)values('方便面',5,'北京','零食'),('牙膏',12,'西安','日用品'),('麻辣条',2,'黑龙江','零食'),('Mac电脑',2000,'美国','电子'),('洗面奶',35,'西安','日用品'),('锅巴',8,'河南','零食');

 

3. 查询同一种类商品(type)的平均价格各为多少

select type,avg(price) from product group by type;

4. 查询零食组商品的平均价格为多少?

select type,avg(price) from product group by type having type='零食';

5. 按照type和address进行分组,每组的平均价格是多少?

select type,address,avg(price) from product group by type,address;

模糊查询:

select 字段列表 from 表名称 where 字段名 like 匹配条件;

模糊查询中的两个通配符:

1. % 代表任意多个任意字符

2. _ 代表任意一个字符

1. 查询名字中包含'张'的学生记录

select * from student where name like '%张%';

2. 查询姓'张'的学生记录

select * from student where name like '张%';

3. 查询名字包含三个字,并且第二个字为'张'的学生记录

select * from student where name like '_张_';

分页查询

已知当前页为currentPage,每页最多显示的记录数为pageSize,则currentPage页显示的表中的记录为:

select 字段列表 from 表名称 [where 条件] limit (currentPage-1)*pageSize,pageSize;

聚合函数:

1. 查询班级的最高分

select max(score) from student;

2. 查询班级的平均分

select avg(score) from student;

3. 查询班级的总分

select sum(score) from student;

4. 查询班级中成绩不为null的记录数

select count(score) from student;

5. 查询班级中的总记录数

select count(*) from student;

6. 通过计算的方式查询班级的平均成绩

select sum(score)/count(score) from student;

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值