五、select的5种子句

1.Where 条件查询
比较运算符:
运算符
说明
>
 
<
 
=
 
>=
 
<=
 
!=<>
 
In
在某集合内
between
在某范围内
In举例:
列出商品表里面cat_id列为45的列:
select goods_id,cat_id,goods_name from goods where cat_id in (4,10);
Between举例:
列出商品表里面商品价格在2000-3000元之间的商品
select * from goods where shop_price between 2000 and 3000;
逻辑运算符:
运算符
说明
not 或 !
逻辑非
or  ||
逻辑或
and  &&
逻辑与
Andor举例:
列出商品价格在3000-5000之间或者在500-1000之间的商品:
select * from goods where shop_price >=3000 and shop_price <=5000 or shop_price >=500 and shop_price <=1000;
not举例:
列出cat_id 不是45的栏目:
select  * from goods where cat_id not in (4,5);
模糊查询:
案例:想查找“诺基亚”开头的所有商品
Like
%------通配任意字符
_------通配单个字符
select * from goods where goods_name like ‘诺基亚%’
2.Group by 分组
统计函数:
求最大:max()
求最小:min()
求总和:sum()
求平均:avg()
求总行数:count()
 
案例:查询每个栏目下面最贵的商品价格(cat_id即栏目)
select cat_id,max(shop_price) from goods group by cat_id;
案例:查询商品的库存总和
select  sum(goods_shuliang) from goods;
案例:查询商品的平均价格
select avg(shop_price) from goods;
案例:查询本店有多少商品,即多少行
select count(*) from goods;
复杂一点的:体会把列名当成变量看
案例:查询每个栏目下面积压的货款(货款=shop_price*goods_shuliang,栏目就是cat_id
select cat_id,sum(shop_price * goods shuliang) from goods group by cat_id;
给列取别名:
select cat_id as lanmu from goods;
3.Having  筛选
wherehaving 的比较:where 对原始表起作用,对查询出来的结果不起作用,having则对查询出来的结果起作用,可以对查询出来的结果进行筛选。
案例:查询出本店价格比市场价低多少钱,并且把低200元以上的商品选出来:
select goods_id,goods_name,market_price – shop_price as sheng from goods having sheng > 200;
或者
select goods_id,goods_name,market_price – shop_price as sheng from goods where market_price – shop_price >200;
但是如果是以下这样,就是错误的。
select goods_id,goods_name,market_price – shop_price as sheng from goods where sheng > 200;
同上题,只不过查第三个栏目下比市场价低200元以上的商品
Select goods_id,cat_id,market_price – shop_price as sheng from goods where cat_id =3 having sheng >200;
更复杂一点:
案例:查询积压货款超过2万元的栏目,以及该栏目积压的货款
select  cat_id,sum(goods_shuliang * shop_price) as k from goods group by cat_id having k>20000;
更复杂案例:
设有成绩表stu如下:
姓名 科目 分数
张三 数学 90
张三 语文 50
张三 地理 40
李四 语文 55
李四 政治 45
王五 政治 30
赵六 地理 100
赵六 英语 99
赵六 化学 98
试查询两门及两门以上不及格同学的平局分
要求:只见一次select 完成
select 姓名,sum(分数<60) as gk,avg(分数) as pj from stu group by name having gk >= 2 ;
 
思路:
1.先查所有人的平均分,
select 姓名,avg(分数) from stu group by name;
2.看每个人的挂科情况
select 姓名,分数<60 from stu;
3.计算每个人的挂科科目
select 姓名,sum(分数<60) from stu group by name;
然后
select 姓名,sum(分数<60) as gk,avg(分数) as pj from stu group by name having gk >= 2 ;
4.Order by  排序
默认为升序排列:order by asc;
降序排列:order by shop_price desc;
select * from goods order by shop_price desc;
5.Limit     限制结果条数
limit [offset],[N]
offset:偏移量(可选)
N:取出条目
 
取第4-6行:
Limit 3,3;
取前三行:
Limit 3;
limit 0,3;
5个子句是有顺序要求的:where,group by,having,order by,limit
 
思考:取出每个栏目下的最贵的商品?
select * from (select goods_id,cat_id,goods_name,shop_price from goods order by cat_id asc,shop_price desc) as tmp group by cat_id;
注解:红色部分用小括号扩起来的部分是查询结果,我们用小括号扩起来就是把他当成一张表看,并且去别名为tmp,然后通过select * from对这张临时表进行查询。
 
 
posted @ 2019-08-12 13:35  Paco_Pig  阅读(332)  评论(0编辑  收藏  举报