数据查询补充

1)简单查询
select Code as‘代号’,Name as ‘姓名’from <表名> //更改列名,换表头

(6)聚合函数(统计查询)
select sum(Price) from Car #查询所有价格之和 sum()求和,只能是数字类数据
select count(*)from Car #查询数据条数 --(*)是查询所有列
select max(Price)from Car #查询价格最高的
min()求最小值

avg()求平均值(不能求字符串)

(7)分页查询
select * from Car limit (n-1)*m,m     // n为页数,m为每页条数

(8)去重查询
select distinct Brand from Car //去除brand列中重复的项 -- distinct去重关键词

(9)分组查询
select count(*),Brand from Car group by Brand //根据Brand列进行分组,统计每个相同名字出现的次数,显示次数和Brand两列   group by分组关键词
select Brand from Car group by Brand having count(*)>3 //查询brand列中出现超过3次的数据 -- 分组之后根据条件查询使用having 不使用where

2)高级查询

1.连接查询,对列的扩展

select * from Info,Nation #形成笛卡尔积

样式1

select <表名>.<列名>,<表名>.<列名>······from <表1>,<表2>
select Info.Code,Info.Name,Info.Sex,Nation.Name,Info.Birthday from Info,Nation where Info.Nation = Nation.Code //查询两个表中的数据,显示在一个表中,并且不显示相同意义的项,表名与列名用‘.’分开

样式2

select * from Info join Nation   //用join连接两个表
select * from Info join Nation on Info.Nation = Nation.Code  //条件查询,关键词 join <表名> on 条件

2.联合查询,对行的扩展

select Code,Name from Info
union
select Code,Name from Nation  //查询Info和Nation两个表中的Code和Name两列的数据,数据类型不相同也不影响,是以增加行的形式

3.子查询

(1)无关子查询

外层查询 (里层查询)
子查询的结果当做父查询的条件

子查询:select Code from Nation where Name='汉族'
父查询:select * from Info where Nation = ''

select * from Info where Nation = (select Code from Nation where Name='汉族')


(2)相关子查询
查询汽车表中油耗低于该系列平均油耗的所有汽车信息

父查询:select * from Car where Oil<(该系列平均油耗)
子查询:select avg(Oil) from Car where Brand = '某个系列'

select * from Car a where Oil<(select avg(Oil) from Car b where b.Brand = a.Brand )  //将父级列表跟子级列表分别定义为a表跟b表(不可用关键字符命名),以与父级列表相关的数据作为子级列表的条件调用

原文地址:https://www.cnblogs.com/m-m-g-y0416/p/5532669.html