Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

postgresql - Updating database columns based on returned results from a SQL Select statement

I have a simple table, which is queried from my backend every minute.

id (int) | phone_number (string) | start (timedatestamp) | period (string) | occurances (int)

I make an sql query, which runs every minute, and returns the results. It's selects all phone_numbers which start this minute.

SELECT * FROM table 

WHERE start >= date_trunc('minute', now()) and
      start < date_trunc('minute', now()) + interval '1 minute'

as results

This runs fine, but I need to update the table as well, based on this select results.

There are two parts to this:

  1. For each selected row, I need the occurrences to decrement by 1 and update the database with this
  2. For each selected row, if the periodicity='MONTHLY", I need the start column to change to the date and time exactly a month from now.

Is it possible to do this in one SQL statement? Any help or examples are greatly appreciated :)

question from:https://stackoverflow.com/questions/65904296/updating-database-columns-based-on-returned-results-from-a-sql-select-statement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes and you can do so directly. The only 'twist' is when a column in mentioned in the SET clause Postgres always writes the Rvalue. When you desire to conditionally update a column you set the Rvalue to the existing value when the condition is not meet. See fiddle here.

update atable 
   set occurances = occurances-1 
     , start_tm = case when period_txt = 'Monthly' 
                       then now()+interval '1 month'
                       else start_tm
                  end
 where date_trunc('minute',start_tm) = date_trunc('minute',now()); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...