postgresql 中的更新和连接语句
本文将引导你使用 update
和 join
语句更新表。
在 postgresql 中生成发货示例
考虑一家销售食品的商店。每当货物到达时,产品的价格就会更新以反映当前的市场价格。
在此示例中,有两个表:produce 和 shipment。
生产表:
|id | price|
-----|-------
| 1 | 0|
| 2 | 0|
| 3 | 0|
| 4 | 0|
| 5 | 0|
| 6 | 0|
| 7 | 0|
| 8 | 0|
| 9 | 0|
| 10 | 0|
createtableproduce(idintegernotnullgeneratedalwaysasidentity,priceintegernotnull,constraintpk_produceprimarykey(id))
这是用默认成本 0 填充 produce 表的 insert
语句:
insertintoproduce(price)select0fromgenerate_series(1,10)i
出货表:
|id | produce_id | produce_price|
-----|------------|---------------
| 1 | 1 | 193|
| 2 | 2 | 41|
| 3 | 3 | 184|
| 4 | 4 | 192|
| 5 | 5 | 174|
| 6 | 6 | 122|
| 7 | 7 | 70|
| 8 | 8 | 130|
| 9 | 9 | 105|
| 10 | 10 | 176|
createtableshipment(idintegernotnullgeneratedalwaysasidentity,produce_idintegernotnull,produce_priceintegernotnull,constraintpk_shipmentprimarykey(id),constraintfk_shipment_produceforeignkey(produce_id)referencesproduce(id))
这是用测试数据填充 shipment 表的 insert
语句:
insertintoshipment(produce_id,produce_price)selecti,floor(random()*(200-201))20fromgenerate_series(1,10)i
使用 update
和 join
语句更新 postgresql 中的表
produce 表中的 price 字段从货件的 produce_price
字段更新,如下所示:
updateproducesetprice=s.produce_pricefromshipmentassleftjoinproduceaspons.produce_id=p.idwhereproduce.id=p.id
仅使用 update
语句更新 postgresql 中的表
可以仅使用 update
语句来实现优化且更简洁的方法,如下所示:
updateproduceaspsetprice=s.produce_pricefromshipmentasswherep.id=s.produce_id
输出:
|id | price|
-----|-------
| 1 | 193|
| 2 | 41|
| 3 | 184|
| 4 | 192|
| 5 | 174|
| 6 | 122|
| 7 | 70|
| 8 | 130|
| 9 | 105|
| 10 | 176|
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
在一个 postgresql 查询中使用多个 with 语句
发布时间:2023/03/20 浏览次数:337 分类:postgresql
-
在本教程中,我们将学习如何使用多个 with 语句在 postgresql 中使用两个临时表执行查询。
发布时间:2023/03/20 浏览次数:185 分类:postgresql
-
本文介绍如何在 ubuntu 上找到 postgresql 数据库的配置文件。
发布时间:2023/03/20 浏览次数:409 分类:数据库
-
本文解释了如何直接从终端/命令行或 psql shell 运行 sql 文件。为此,你需要指定主机名、端口、用户名和数据库名称。
发布时间:2023/03/20 浏览次数:89 分类:postgresql
-
本文展示了如何列出 postgresql 上的活动连接。
在 postgresql 中使用循环
发布时间:2023/03/20 浏览次数:966 分类:postgresql
-
在 pl/sql 中,你可能需要在 postgres 中使用循环。我们可以使用 for 和 while 语句来创建循环。
发布时间:2023/03/20 浏览次数:141 分类:postgresql
-
本文介绍如何在 postgresql 中仅使用单个查询来重命名列以及更改其类型。
发布时间:2023/03/20 浏览次数:233 分类:postgresql
-
本文介绍如何在 postgresql 中使用 select 方法连接列。
发布时间:2023/03/20 浏览次数:281 分类:postgresql
-
本文展示了如何使用 case 语句并给出了 postgresql 中的示例。