– 增加
insert into 表名(列名)values(值);
– 修改
update 表名 set 列名=新值,列名=值 where 保证修改的时候只修改了一条记录;
– 删除
delete from 表名 where 主键:保证修改的时候只修改了一条记录;
– 查询
select 列名 from 表名 where;-- 条件查询
select * from score;
select * from student;
– 分组函数又叫聚合函数
– avg(列名):求平均值
– 1.求科目编号是1的平均分
select avg(socre) from score where english is not null ;
– 2.max(列名):求最大值 min(列名):求最小值
– 求科目编号是1成绩的最高分和最低分
select MAX(socre),MIN(socre) from score ;
– 3.sum(列名):求和
– 查询学生编号是1所有科目的总成绩
select sum(socre) from score where stuid=1;
– count(列名):统计
– 查询本校一共有多少学生
select COUNT(*) from student;
– 各科目都已考完,成绩已出来,
– 怎么获取各科目的平均成绩呢?
– 1.查询哪些科目参加了考试
select DISTINCT subid from score;-- 去重
– 2.对每个科目求平均值
select avg(socre) from score where subid=1;
select avg(socre) from score where subid=2;
select avg(socre) from score where subid=3;
select avg(socre) from score where subid=4;
– 只要这个题目出现了各 或者 每 肯定是分组
– 如果使用了分组函数,考虑是否使用分组
– GROUP BY:分组 把字段相同的值分到个组里面
select avg(socre),scoid from score GROUP BY subid;
– 如果使用SqlServer这里需要注意:select后面有几列,在group by后面
– 写几列,聚合函数除外
– 查询出所有成绩加5分后,成绩还是小于60分的学生学号
– where:对查询结果进行筛选,针对于表中真正存在的列起作用,where
– 作用在group by之前
– having:对查询结果进行筛选,针对于查询结果的列起作用
– having作用在group by 之后
select stuid,socre+5 成绩加5分 from score where 成绩加5分<60
select stuid,socre+5 成绩加5分 from score HAVING 成绩加5分<60
– SqlServer的having不能单独有,必须配合group by用,mysql可以单独用
– 查询平均成绩大于70分的各科目的平均成绩
select AVG(socre) from score GROUP BY subid HAVING avg(socre)>70;
select * from student;
– order by:排序
– asc:升序:默认值
– desc:降序排列 由高到低
– 查询所有学生信息,根据cid升序排列
select * from student ORDER BY cid;
select * from student ORDER BY cid desc;
– 可以根据多个字段排序
select * from student ORDER BY cid asc,birthday desc;
– LIMIT(数据的下标,显示的条数),数据的下标从0开始
– 查询年龄最大的五名学生的信息
select * from student ORDER BY stuid asc LIMIT 0,5;
select * from student ORDER BY stuid asc LIMIT 5,5;-- 也可以
select * from student ORDER BY birthday asc LIMIT 5,10;
– 常用函数
– 1.获取当前系统日期和时间
select CURRENT_DATE(),CURRENT_TIME();
– 年月日,时分秒
select NOW(),CURRENT_TIMESTAMP();
– 2.获取字符串的长度
select LENGTH(name) from student;-- 汉字占用三个字节
– 3.拼接字符串
select CONCAT(stuid,name) from student;
select CONCAT(stuid,’(’,name,’)’) from student;
– 4.大小写转换
select UCASE(name) as 大写,LCASE(name) as 小写 FROM student;
SELECT socre,IF(socre>=60,‘及格’,‘不及格’) AS 等级 from score;