简体   繁体   English

如何按计划更新PostgreSQL表中的值?

[英]How do I update a value in a table in PostgreSQL on a schedule?

Let's say I have a vet application, and there're 2 databases(let's say doctors perform operations): 假设我有一个兽医应用程序,并且有2个数据库(假设医生执行手术):

User database with fields : id, email, name, password and regStamp. 用户数据库,包含以下字段: ID,电子邮件,名称,密码和regStamp。

PetOperations database with fields: id, id(reference to user), doctorName, operationStamp and operationStatus. PetOperations数据库,具有以下字段: id,id(对用户的引用),doctorName,operationStamp和operationStatus。

What if I want to update a operationStatus field whenever someone puts a new petOperation in Pet database(initial status was PERFOMING after 20 minutes it becomes PERFORMED, but only for this unique operationId, if currentTime - operationStamp >=20). 每当有人将新的petOperation放入Pet数据库时(如果初始状态为PERFOMING,在20分钟后它将变为PERFORMED,但仅针对此唯一的operationId,如果currentTime-operationStamp> = 20),我想更新operationStatus字段怎么办? How can I do that? 我怎样才能做到这一点? Maybe, there's a better way rather than subtraction times? 也许有比减时间更好的方法了吗?

I think you need to rethink your data model a little bit. 我认为您需要重新考虑一下数据模型。 As I understand your question you have operations which are scheduled, and you want to treat them as performed after the scheduled time slice is complete. 据我了解您的问题,您有已计划的操作,并且您希望将其视为在计划的时间片完成后执行。

PostgreSQL has no native facility to update a value in 20 minutes. PostgreSQL没有本机工具可以在20分钟内更新值。 You could use a cron job, but I think the more elegant solution is to change your data model instead. 您可以使用cron作业,但是我认为更优雅的解决方案是更改数据模型。

Add a "table method" and you get status calculation. 添加一个“表方法”,您将获得状态计算。

suppose your table now contains: 假设您的表现在包含:

id, id(reference to user), doctorName, operationStamp, operationTsrange

Then you create a function something like: 然后创建一个类似以下的函数:

create or replace function status(operation) returns text language sql
as $$
     select case when $1.operationTsrange is null then 'Not Scheduled'
                 when now() << $1.operationTsrange THEN 'Scheduled'
                 when now() <@ $1.operationTsrange THEN 'Performing'
                 when now() >> $1.operationTsrange THEN 'Performed'
             END;
$$;

Then you can search on this. 然后,您可以对此进行搜索。 And if you need different length intervals you can specify them on update time. 如果需要不同的长度间隔,可以在更新时间指定它们。

I am not sure what you want to do. 我不确定您要做什么。

If you just want to set the initial operationstatus when you INSERT a row, use a BEFORE INSERT trigger. 如果只想在INSERT一行时设置初始operationstatus状态,请使用BEFORE INSERT触发器。

If you want the value to change depending on when it is selected, use a “computed column”, that is, don't define the column in the table, but rather define a view on the table that contains the column, calculated as appropriate. 如果要根据选择的时间来更改值,请使用“计算列”,即,不要在表中定义该列,而是在包含该列的表上定义一个视情况而定的视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM