group分组与统计函数:
统计函数:
max()
count()
avg()
min()
sum()
在sql中重复要用的语句:用as名字新变量,以便调用
select goods_id,goods_name,(market_price-shop_price) as save from goods
having -- 对查询出来的结果集进行筛选
where 不能写在having后面
order by :(默认升序asc) 降序asc(排序很浪费资源)
select goods_id,goods_name,shop_price from goods order by shop_price desc;
limit用法:(做分页类能用到)
限制取出条目(limit有两个参数 :偏移量 取出的条目)
select goods_id,goods_name,shop_price
-> from goods
-> order by shop_price desc
-> limit 0,3;
子句的查询陷阱:
5种语句有严格的顺序,where ,group by,having,order by,limit
不能颠倒顺序
例子: #语句有严格的顺序
mysql> select id,sum(num)
-> from
-> (select * from a union select * from b) as temp
-> group by id
-> having sum(num)>10
-> order by sum(num) desc
-> limit 0,1;
子查询:
where字查询:(内层的查询结果作为外层的比较条件)
静态的:select goods_id,goods_name from goods where goods_id=32;
动态的:select goods_id,goods_name from goods where goods_id=(select max(goods_id) from goods);
#取出每个栏目下最新的商品:
select goods_id,cat_id,goods_name from goods where goods_id in (select max(goods_id) from goods group by cat_id);
from子查询:
#每个栏目下最新的商品:
mysql> select goods_id,goods_name from (select * from goods where 1 order by cat_id desc) as tmp
-> group by cat_id;
exists子查询:
#查询栏目下是否有商品
mysql> select * from category
-> where exists(select * from goods where goods.cat_id=category.cat_id)