设为首页 加入收藏

TOP

学习数据库笔记四
2015-11-21 01:52:48 来源: 作者: 【 】 浏览:0
Tags:学习 数据库 笔记

基本操作?

怎么建立一张表,和给表中添加数据

create table temp(

id int,

name varchar(20)

)charset utf8;

给表中添加多条数据

insert into temp values(1,'Lucy'),(3,NULL),(5,'XiaoMing'); 不想写可以写NULL

值为NULL时怎么查询?

NULL比较特殊,用=查不出来,需要用is和is not

查询名字为空的数据

select id,name from temp where name is null;

查询名字不为空的所有数据

select * from temp where name is not null;

group by分组与统计函数?

统计函数也叫聚合函数,有如下这些

max 求最大

min 求最小

avg 求平均

count 求行数

sum 求总合

求商品价格的平均数 select avg(shop_price) from goods;

求最贵的商品select max(shop_price) from goods;

总共有多少商品select count(*) from goods;

商品一共多少钱select sum(goods_number*shop_price) from goods;

像上面这样单单统计的情况少,工作中的情况比这复杂的多,一般都会用到group by + 统计

group by分组其实很耗费资源,因为它会先进行一个排序的功能

group by + 统计练习?

求每个栏目中商品的平均价格

select goods_id,cat_id,avg(shop_price) from goods group by cat_id; 所有查询都要遵守“查询模型” ,先看条件,再由条件决定变量,这里是先分组,然后变量里计算出每一组的平均价格。

求每个栏目下商品的数量?

思路,每个栏目-->分组 商品的数量-->统计 用group by + 统计函数组合

select goods_id,goods_name,cat_id,count(*) from goods group by cat_id;

求每个栏目下最贵的商品?

select cat_id,max(shop_price) from goods group by cat_id;

having筛选

它和where的区别是,where条件是针对硬盘上的表中的数据,而having筛选的是内存中的结果集中的数据。

如果两个同时出现,where肯定要放在having前面的,因为结果集还没有出现,先从硬盘上查出结果集才能having。

查询出比市场价格便宜200块以上的商品

思路,比市场价格便宜多少钱-->减法运算得出结果集 便宜200块-->结果集中大于200的

select goods_id,goods_name,(market_price-shop_price) as sheng from goods having sheng >= 200;

*结果集起别名的时候,as和别名要放在括号外面(market_price-shop_price) as sheng

order by 排序 (之前的是group by ,是分组)

硬盘上的文件,有可能是直接排好序的,也可能没排好序,没排序的只好到内存中再次排序,比较浪费资源,应尽量避免,也就需要你建立良好的索引,避免再次排序,这属于数据库优化部分。

降序 desc [和查看表结构的命令是一样的,但作用不同,注意区分]

升序 asc [默认是asc]

1.把价格按升序排序

select goods_name,shop_price from goods order by shop_price asc;

2.把商品先按栏目排序,再把每个栏目中的商品按价格排序

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

如果想把一组东西彻底排序,先按id排序,之后同一类id中再按价格排。只需要在排序的字段后加个逗号,接着排

limit 限制取出条目

limit能选择性的帮助我们拿出一条或几条数据。它一般和order by配合使用(group by + 统计函数配合使用)

limit有两个参数,第一个参数是你要跳过几行,第二个是取几行

limit 0,3 参数是木有括号的哦!

1.取出价格最高的前三名商品

select * from goods order by shop_price desc limit 0,3;

2.查出最新的商品来(id最大的商品最新,因为id是自增的)

select * from goods order by goods_id desc limit 0,1;

Oracle下没有limit,只有mysql有,分页时会用limit

子句的查询陷阱(子句的顺序)

顺序如下

where / group by / having / order by / limit

这5种子句是有严格顺序的!

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇重构机房收费系统―数据库设计 下一篇Redis数据类型之字典

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: