PostgreSQL查询一个表的数据
要从一个表中检索数据就是按要求查询表的信息,。SQL的SELECT语句可分为:
1.选择列表(选择查询返回的列)
2.表列表操作(从中查询出的数据,进一步进行加减乘除=-*/、筛选等操作)
3.可选的条件 where查询条件或者排序去重等。
上节最后清空了weather表数据,现在加上了数据:
insert into weather values (1,'北京', 1, 37, 0.55, '2025-05-12');
insert into weather values (2,'上海', 10, 41, 0.65, '2025-05-12');
INSERT INTO weather (id,city, temp_low, temp_high, prcp, date) VALUES (3,'广州', 15, 33, 0.74, '2025-05-12');
INSERT INTO weather (id,city, temp_low, temp_high, date) VALUES (4,'深圳', 14, 32, '2025-05-12');
insert into weather values (5,'杭州', 2, 38, 0.75, '2025-05-12');
insert into weather values (6,'西安', 1, 36, 0.35, '2025-05-12');
执行后如图:
一.选择列表
查询表weather的所有行:
-- *是“所有列”的缩写
select * from weather;
完整的查询结果如下:
select id,city, temp_low, temp_high, date from weather;
二.表列表操作
选择列表中按需求写任意表达式,而不仅仅是所有列表。
select
city , (temp_low+temp_high)/2 as temp_avg , date
from weather;
(temp_low+temp_high)/2 as temp_avg :将最低温度和最高温度相加除以2,得到平均温度, as 表示别名,是输出后重新给这段语句的命名,也可以不要。
三.可选的条件
查询可以使用WHERE指定需要哪些行。
正式表达是WHERE子句包含一个布尔(真值)表达式,只有布尔表达式为真的行才会被返回。
在条件设置时常用布尔操作符:和and、或or、非not 。
比如查询天气表种杭州的最高温度大于30°数据:
select * from weather
where city = '杭州'
and temp_high >30 ;
结果:
另一个返回的查询结果是经过排序的:
select * from weather order by id desc;
select * from weather
order by temp_high, id desc;
-
order by id 是默认id按小到大的顺序。
-
order by id desc 表示id按从大到小的顺序。
-
order by temp_high, id 表示按照从temp_high按小到大顺序, 之后按照id按小到大顺序
-
order by temp_high desc, id asc 表示按照从temp_high按大到小顺序, 之后id默认按小到大顺序
最后可以组合使用distinct(去重) 和 order by :
select distinct city from wheather order by city;
可以新增多条不同日期同一个城市的数据进行尝试。
完!