【问题标题】:I have a table with a status however I want it to change status every 10 minutes. I'm using Postgresql我有一个状态表,但我希望它每 10 分钟更改一次状态。我正在使用 Postgresql
【发布时间】:2020-01-19 21:02:49
【问题描述】:

我想将表的值从一种状态更改为另一种类型 'A’ 并在 10 分钟后使用 python 将其变为 'B' postgres。

【问题讨论】:

    标签: python postgresql


    【解决方案1】:

    虽然有一个很大的遗漏,但我可以看到您在追求什么:当状态达到“Z”并且该更新时会发生什么?稍后会详细介绍。

    您的请求包含 2 个组件,实际上是运行一个进程和一个滚动更新程序(脚本)的状态。好吧,Postgres 没有用于启动脚本的本机功能。您必须设置一个 cron 作业,或者一个条目就是您拥有的作业调度程序。更新过程并不是那么困难,除了未定义的“Z”状态问题。 (所以当这种情况发生时,我将重复 A-Z 扩展代码长度(有点像 excel 名称列)。

    所需的基本更新是简单地将当前值加 1。但是当然语句“'A'+1”不起作用,但是可以使用CHR and ASCII函数获得结果。 Chr(ascii('A')+1)) 有效地完成了这一点,因此您的更新可以完成为:

    Update table_name set status = chr(ascii(status)+1);
    

    但是,一旦状态达到“Z”,就会失败。好吧,它不会因为生成错误而失败,但会产生'['。以下脚本在上述情况下生成“AA”,每次状态达到“...Z”时,下一个状态变为“...AA”。

    --- setup 
    drop table if exists current_stat;
    create table current_stat(id serial,status text,constraint status_alpha_ck check( status ~ '^[A-Z]+'));
    insert into current_stat(status) values (null), ('A'), ('B'), ('Y'), ('Z'), ('AA'), ('ABZ')
    
    --- Update SQL
    with curr_stat as
       ( select id, status
              , chr(ascii(substring(status,char_length(status),1))+1) nstat
              , char_length(status) lstat from current_stat)  
    update current_stat cs
      set status = ( select case when status is null or lstat < 1     then 'A'
                                 when substring(status,lstat,1) = 'Z' then overlay( status placing 'AA' from lstat for 2)
                                 else overlay( status placing nstat from lstat for 1)
                            end
                       from curr_stat
                   where cs.id = curr_stat.id
                 );
    
    select * from current_stat;
    

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 2020-12-19
      • 2021-01-13
      • 2018-12-13
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多