Mysql表格中语句查询
-语句顺序查询
1.语句查询执行顺序
3、select 聚合函数 from 表名
1、where 条件
2、group by ...
4、having ...
5、order by ...
6、limit ..
先创建一个表格如下,示例说明Mysql查询语句的使用方法
创建表格代码:
create table sanguo(
id int,
name char(20),
gongji int,
fangyu tinyint unsigned,
sex enum("男","女"),
country varchar(20)
)default charset=utf8;
insert into sanguo values
(1,'诸葛亮',120,20,'男','蜀国'),
(2,'司马懿',119,25,'男','魏国'),
(3,'关羽',188,60,'男','蜀国'),
(4,'赵云',200,66,'男','魏国'),
(5,'孙权',110,20,'男','吴国'),
(6,'貂蝉',666,10,'女','魏国'),
(7,null,1000,99,'男','蜀国'),
(8,'',1005,88,'女','蜀国');在这里插入代码片
表格如下
2、group by :给查询的结果进行分组
2.1计算每个国家的平均攻击力
select country,avg(gongji) from sanguo group by country;
2.2查找所有国家英雄中,英雄数量最多的国家的前2名,显示国家名称和英雄数量
select country,count(id) as number from sanguo
group by country
order by number desc
limit 2;
3、having语句 :对分组聚合后的结果进一步筛选
3.1找出平均攻击力>105的国家的前2名,显示国家名称和平均攻击力
select country,avg(gongji) from sanguo
group by country
having avg(gongji)>105
order by avg(gongji) desc
limit 2;
3.2注意
having语句通常和group by语句联合使用,having语句弥补了where关键字不能与聚合函数使用的不足,where只能操作表中实际存在字段
4、distinct :不显示字段的重复值
4.1 表中有哪些国家
select distinct country from sanguo;
4.2计算蜀国有多少个英雄
select count(distinct id) as number from sanguo
where country="蜀国";
5、查询表记录时做数学运算
+ - * / %
查询时所有英雄攻击力翻倍
select name,gongji*2 as xgj from sanguo;
-嵌套查询(子查询)
1、定义 :把内层的查询结果作为外层的查询条件
2、select … from 表名 where 字段名 运算符 (查询);
3、把攻击值小于平均攻击值的英雄名字和攻击值显示
1、先算出平均攻击值
select avg(gongji) from sanguo;
2、找小于平均值
select name,gongji from sanguo where gongji<..
3、嵌套查询实现
select name,gongji from sanguo where gongji<(select avg(gongji) from sanguo);
4、找出每个国家攻击力最高的英雄的名字和攻击值
select name,gongji from sanguo
where
(country,gongji) in (select country,max(gongji) from sanguo group by country);