SQL(PostgreSQL)使用来自JOIN表中数据的间隔更新日期列

发布于 2025-02-03 21:39:55 字数 1707 浏览 3 评论 0 原文

在我的PostgreSQL数据库中,我试图根据该表和另一个表中的数据更新一个表中的列。在我的用户表中,我正在尝试通过在我的计划表中的几个月中的几个月(例如new_date = 2022-02-27 + 5个月)中将数据添加到整数列中来更新New_date列。如果这是一个表,我可以添加日期 +间隔'1个月 *月,例如 - 更新用户设置new_date = date + Interval'1个月 *月; ,但是,我是无法弄清楚如何使用用户和计划之间的联接表(具有子查询或常见表表达式)进行类似的更新。

缩写): new_date 将根据日期 + 月份

进行 更新
用户表 null
2022-04-15 null

计划表(缩写)

5月
1

结合表:select users.date.date,planths.new_date,users.new_date,来自用户的new_date从用户加入unders.plan_id = plans.id

date。 new_date
2022-05-21 5
2022-04-15 1

结果:

更新用户表

日期 new_date
2022-05-21 2022-10-21 2022-21
2022-04-15 2022-05-15

In my Postgresql database, I am trying to update a column in one table based on data in that table and another table. In my users table, I'm trying to update the new_date column by adding data in a separate date column to an integer column in months from my plans table (e.g. new_date = 2022-02-27 + 5 months); if this was a single table I could add date + interval '1 month' * months, such as something like - UPDATE users SET new_date = date + interval '1 month' * months; However, I am unable to figure out how to do a similar update using a join table between users and plans, with subqueries or common table expressions.

users table (abbreviated): new_date to be updated based on date + months

date new_date
2022-05-21 null
2022-04-15 null

plans table (abbreviated)

months
5
1

join table: SELECT users.date, plans.months, users.new_date FROM users JOIN plans ON users.plan_id = plans.id

date months new_date
2022-05-21 5
2022-04-15 1

Result:

updated users table:

date new_date
2022-05-21 2022-10-21
2022-04-15 2022-05-15

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

踏月而来 2025-02-10 21:39:55

您可以加入表,并将列的值乘以月份 Interval'1个月' update> update> update 语句中:

UPDATE users AS u
SET new_date = u.date + INTERVAL '1 month' * p.months
FROM plans AS p
WHERE p.id = u.plan_id;

请参阅 demo demo 。

You can join the tables and multiply the value of the column months by INTERVAL '1 month' in the UPDATE statement:

UPDATE users AS u
SET new_date = u.date + INTERVAL '1 month' * p.months
FROM plans AS p
WHERE p.id = u.plan_id;

See the demo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文