您的位置:首页 > 数据库 > MySQL

再次认识mysql(二)

2016-08-29 17:35 211 查看
group 分组与统计函数

max()求最大  min()求最小   sum()求总和  avg()求平均   count()求行数 有多少行

select sum(goods_num*shop_price) from goods; 查询库存所有的价值金额 

select cat_id,avg(shop_price) from goods group by cat_id; 根据id分组  计算平均值

select cat_id,count(*) from goods group by cat_id;  查询每个栏目下商品数量

select cat_id,max(shop_price) from goods group by cat_id;查询每个栏目下最贵的商品价格

having:对结果集的再次筛选

select goods_id,goods_name,<market_price-shop_price> as jieyue from goods where jieyue>300;  典型错误 where会在磁盘中进行筛选  发现并没有jieyue 列

select goods_id,goods_name,<market_price-shop_price> as jieyue from goods having jieyue >300;

查询成绩2门及2门以上不及格的 学生 的平均分

思路:以结果为导向 先查找 所有学生 平均分和不及格数目    再在结果集中寻找2门以上挂科的

select name,avg(score) as pingjunfen,sum(score<60) as guake  from user  group by name   having  guake>=2;

order by 排序

利用行字段排序

升序 默认 asc       降序 desc 

多列排序  逗号隔开

select goods_id,cat_id,goods_name from goods order by cat_id  asc,shop_price,goods_id desc;

limit 限制取出条目

常用于分页

select  goods_id from goods order by shop_price desc  limit 3; 取出前三名价格最高的

select  goods_id from goods order by shop_price desc  limit 2,3; 取出  前  第三名  到第五名 价格的商品

查询陷阱

where group  by  having order by limit   五种限定词的顺序不可颠倒

子句查询

寻找最新的商品

1   select goods_id from goods order by goods_id dedc limit  0,1;

2   select goods_id from goods where  goods_id=(select max(goods_id) from goods);   where类型子查询  内层查询结果是外层的比较条件

from类型子查询   

select goods_id from (select goods_id from  goods order by cat_id asc,goods_id desc) group by cat_id;

exist类型子查询

select *from category where exists (select *from goods where goods.cat_id=cate.cat_id);

内连接

select * from table1 inner join table2  on table1.xx=table2.xx;

左右连接

select * from table1 left join table2 on table1.xx=table2.xx;    侧重于显示左侧  查不到 的null

select *from table2 right join table2 on table1.xx=table2.xx;   侧重于显示右侧  查不到的null

单张表连续左连接

select mid,t1,tname as hteam,mres,t2.tname as gteam,matime

            from m inner join t as t1 on m.hid=t1.tid inner join t as t2  on m.gid=t2.tid

            where matime between '2006-6-1'and '2006-7-1';

union查询 

  将多条sql查询结果合并成一个结果集  必须满足 各语句取出的列数相同   列名称以第一条为准   

   完全相等的列 将会被合并   合并过程非常耗时

   不丢失列  union  all       

   select  id,sum(num)  from (select *from a union all select *from b) as tmp group by id;

   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql