mysql常用操作汇总(五)

数据结构:


1.汇总函数:

avg(), count(), max(), min(), sum()

select avg(price), count(price), max(price), min(price), sum(price) from shopping;


2.数据分组:

mysql提供了数据分组的方法,group by对列数据进行分组统计

select price,count(price) from shopping group by price; 


3.过滤分组,行的过滤可以使用where,having,分组的过滤只能使用having,不能用where

select price,count(price) from shopping group by price having price='66'; 


注意:

1.关键字使用顺序

select xxx from xxx group by xxx order by xxx limit xxx;

select xxx from xxx where xxx order by xxx limit xxx;

2.group by的功能是进行分组,order by 是排序,各司其职,group by的排序不靠谱

4.联结表(联结表是对两个及以上的表进行筛选)

select shopping.name,custom.name,custom.id from shopping,custom where shopping.id = custom.id order by custom.id;

可以使用表别名降低select语句的长度 select a.name,b.name b.id from shopping as a ,custom as b where a.id=b.id order by b.id;


如果没有where的筛选规则,则根据笛卡儿积的规则返回两个表的m*n数据组合

select shopping.name,custom.name,custom.id from shopping,custom;


mysql还可以通过inner join ... on的方式进行联结表的查询

select shopping.name as shopping_name, custom.name as custom_name, custom.id as custom_id from shopping inner join custom on shopping.id=custom.id order by custom.id;

还可以使用别名,降低select语句的长度select a.name,b.name,b.id from shopping as a inner join custom as b on a.id=b.id order by b.id;


注意:

表别名和列别名不一样,表别名不会作为真实数据返回,列别名会做为真实的字段返回

5.组合查询

在需要获取两个表中同样的数据时,可以使用组合查询的方式,关键字为union

select name,id from shopping union select name,id from custom;


同样也可以在一个表里面使用组合查询,在筛选条件不同时可以使用

select name,id from shopping where id<='2' union select name,id from shopping where id='5';


注意:使用组合查询时,返回的结果必须是一样的,必须对同一个表或者不同的表返回查询结果的字段必须相同

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值