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 , datefrom 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;      
  1. order by id 是默认id按小到大的顺序。

  2. order by id desc 表示id按从大到小的顺序。

  3. order by temp_high, id 表示按照从temp_high按小到大顺序, 之后按照id按小到大顺序

  4. order by temp_high desc, id asc 表示按照从temp_high按大到小顺序, 之后id默认按小到大顺序

最后可以组合使用distinct(去重) 和 order by :

select distinct city from wheather order by city;

可以新增多条不同日期同一个城市的数据进行尝试。

完!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小何慢行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值