简体   繁体   中英

postgresql INSERT INTO with IF statement

In postgresql , how to INSERT values in a column.b from column.a from same table Where

IF column.a = 1 then column.b = foo, 
IF column.a = 2 then column.b = bar,
IF column.a = 3 then column.b = good,
IF column.a = 4 then column.b = bad

INSERT does not insert values into columns. It inserts new rows into your table. Instead, you need to use an UPDATE statement . You will also need some ifs inside .

If the row already exists, you do not need an INSERT . You need an UPDATE like this:

UPDATE your_table
SET b = CASE 
        WHEN a = 1 then 'foo'
        WHEN a = 2 then 'bar'
        WHEN a = 3 then 'good'
        ELSE 'bad'
        END
WHERE some_condition = 'true';

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