简体   繁体   中英

Insert data from column to another different table column with modifying in PSQL

I have a table called log that contains a column called time which is a time stamp with time zone, I wanna remove the time and only leave the date then put the modifying result in another column called day in a table called error. For example if the the time column in the log table looks like this the day column in the error table should look like this.

 |---------- time --------|      |-----day-----| 
 | 2016-07-01 09:00:00+02 |      | 2016-07-01  |
 | 2016-07-01 09:00:47+02 |      | 2016-07-01  |
 | 2016-07-01 09:00:34+02 |      | 2016-07-01  | 

INSERT INTO错误(天)(从日志中选择时间::日期)

There's SUBSTRING function in PostgreSQL that can do what you want. You can do an INSERT from a SELECT like this:

INSERT INTO error
    ( day
    )
SELECT SUBSTRING (time::TEXT FROM 1 FOR 10)
FROM log

For more neat functions, check Postgres's Documentation - I'm not sure what version your PostgreSQL is, so this is for version 8.1

If you really want to do this, it should be something like this:

update log
set day = cast (time as date)
where
  day is null or day != cast (time as date);

DML can be expensive, so be sure to not update rows where the value already matches.

That said, don't do that. Either resolve this at query time, or if you want to be really lazy, create a view:

create or replace view log_dated as
select
  l.*, cast (l.time as date) as day
from log l;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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