2.1 select语句基础
2.1.1 select和from语句
从表格中选取数据的时候需要用到select
语句,最简单的语句就是select * from TableName
。通过select
语句查询并且选出数据的过程称之为匹配查询或查询。
基本的select
语句包含了select
和from
两个字句,例如从下表clothes中选出name列的数据
/* 语法:select 列名 from 表名 */
/* 例子:选出下面clothes表中的name列 */
select name from clothes
2.1.2 配合where语句筛选
当不需要取出全部数据,而是选取出满足某些条件的数据时,使用where
语句。
select
语句通过where
子句来指定查询数据的条件。在where
子句中可以指定“某一列的值和这个字符串相等”或者“某一列的值大于这个数字”等条件。执行含有这些条件的select
语句,就可以查询出只符合该条件的记录了。
例子,查找clothes表中price>100的衣服名称,并显示其价格
--使用where语句添加筛选条件
select name, price from clothes where price>100;
2.2 算数运算符和比较运算符
这部分内容比较简单,主要就是根据运算符本身的含义使用,比如>, < 等
例子,首先将表中的price字段更改为可为NULL
-- 使用modify更改price字段的类型
alter table clothes modify price int null;
desc clothes;
接下来,将表中的NiKE的价格更改为NULL
update clothes set price=null where name='NiKe';
select * from clothes;
可以看到,修改为NULL
下面,我们就通过运算符找出其中的price字段不为NULL的衣服名字
select name,price from clothes where price is not null
2.3 逻辑运算符
2.3.1 not运算符
老规矩,先更改一下表格中的数据
update clothes set price=120 where name='NiKe';
select * from clothes;
挑选出其中不大于100的衣服
-- 使用not来表示不怎么样
select name,price from clothes where not price>100;
--等价于下面语句
select name,price from clothes where not price<=100;
2.3.2 and和or运算符
先更改一下clothes这个表,给他新添加一列sales(销量)
-- 使用alter新添加sales列:alter table 表明 add 列名 类型 其他
-- after name表示在name列后添加
alter table clothes add sales int after name;
select * from clothes;
然后给sales字段添加值
update clothes set sales=1000 where name='adi';
update clothes set sales=2000 where name='LiNing';
update clothes set sales=3000 where name='NiKe';
select * from clothes;
然后使用and
选择sales>2000并且price>120的物品
select * from clothes where sales>2000 and price>100;
2.4 对表进行聚合查询
sql中用于汇总的函数叫做聚合函数,下面是最常见的聚合函数
对上面的例子进行一下使用,先看一下最初的clothes表
使用上面的函数
🔰 查看该表的行数
🔰计算sales和price的和
🔰 avg, max等和sum函数同理
2.5 对表进行分组
首先更改数据
-- 先去掉主键,否则name列不允许重复
alter table clothes drop primary key;
-- 给name添加adi列
insert into clothes(name,sales,price) values('adi', 4000, 90);
insert into clothes(name,sales,price) values('adi', 5000, 100);
select * from clothes;
按名字进行分组,可以分为adi, LiNing和Nike三组,查找每组的最大销量
select name as 名字,max(sales) as 最大销量
from clothes
group by name;
2.6 为聚合结果指定条件
将表使用group by
分组后,怎样才能只取出其中两组?
这里WHERE不可行,因为,where
子句只能指定记录(行)的条件,而不能用来指定组的条件(例如,数据行数为 2 行或者平均值为 500等)。可以在group by
后使用having
子句,其中having
的用法类似where
。
之前,我们查找了每个品牌的最大销量
select name as 名字,max(sales) as 最大销量
from clothes
group by name;
现在,我们选出销量>2500的品牌,相当于对上面的表进行又一步处理,这个时候就得用到having
关键字
select name as 名字,max(sales) as 最大销量
from clothes
group by name
having 最大销量>2500;
现在,我们拿where
取出名字为adi的那一列(因为,where
只能拿来确定列的条件,这个列还得是之前和现在都有的列,比如现在的name)
select name as 名字,max(sales) as 最大销量
from clothes
where name='adi'
group by name
having 最大销量>2500;
2.7 对查询结果进行排序
看一下例子,怎么将clothes表中的数据,名字放在一块,按照sales降序排列
当name相同的时候,按照sales的规则进行排列
select * from clothes order by name asc, sales desc;
2.8 习题
关于习题部分,2.3和2.4比较有趣,但是也属于一类提,这里给出一个答案。比如,我的clothes表如下
找出sales比price大1000的数据
select * from clothes where (sales-price)>1000;