准备数据:
create table student(
id int,
name varchar(20),
chinese float,
english float,
math float
);
insert into student (id ,name ,chinese,english,math)values(1,`张小明`,89,78,90);
insert into student (id ,name ,chinese,english,math)values(2,`李进`,67,98,56);
insert into student (id ,name ,chinese,english,math)values(3,`王五`,87,78,77);
insert into student (id ,name ,chinese,english,math)values(4,`李一`,88,98,90);
insert into student (id ,name ,chinese,english,math)values(5,`李来财`,82,84,67);
insert into student (id ,name ,chinese,english,math)values(6,`张进宝`,55,85,45);
insert into student (id ,name ,chinese,english,math)values(7,`张小明`,75,65,30);
查询学生的总成绩
select s.chinese+s.english+s.math,s.name from student s
使用别名
select chinese as 语文,english as 英语,math as 数学,name from student
与下面语句等价
select chinese 语文,english 英语,math 数学,name from student
查询总分大于200分的所有用户
select * from student s where (s.chinese+s.english+s.math)>250
不等于:<> 或者 !=
1 使用order by 排序
order by使用语法:
select column1,column2 from table_name order by 列名 asc[decs]
对数学成绩排序后输出
select math,name from student order by math;
对总分排序后输出
select (s.chinese+s.english+s.math) as sum_score,s.name from student s order by sum_score desc
与下面句子等价
select (s.chinese+s.english+s.math) ,s.name from student s order by (s.chinese+s.english+s.math) desc
对姓李的同学成绩排序
select (s.chinese+s.english+s.math) as sum_score,s.name from student s where s.name like '李%' ORDER BY sum_score desc
2 统计函数
统计函数count语法:
select count(*) | count(列名) from tablename where where_definition
统计数学成绩大于90分的同学
select count(*) from student where math>=90
统计函数sum 和 avg语法
select sum(列名){,sum(列名)…} from table where where_definition
select avg(列名){,avg(列名)…} from table where where_definition
强调:avg不会统计(为空)的现象
统计函数max 和 min语法
select max(列名) from table where where_definition
select min(列名) from table where where_definition
备注:如果数据类型不是“数值”类型,也能进行排序查询
3 group by 分组
create table orders(
id int,
product varchar(20),
price float
);
insert into orders(id,product,price) values(1,'电视',900);
insert into orders(id,product,price) values(2,'洗衣粉',100);
insert into orders(id,product,price) values(3,'洗衣粉',90);
insert into orders(id,product,price) values(4,'桔子',10);
insert into orders(id,product,price) values(5,'洗衣粉',90);
根据商品分类
select product,sum(price) from orders group by product;
having用法
查询购买了几类商品,并且每类总价大于100的商品
select product,sum(price) as sumprice from orders group by product HAVING sumprice >100;