插入中的Postgres CASE语句 [英] Postgres CASE Statement in an insert

查看:83
本文介绍了插入中的Postgres CASE语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张必须在Postgres中更改的表。我现在想根据条件为表中存在的行插入一些值。我正在使用CASE块!

I have a table that i had to ALTER in Postgres. I would now like to insert some values for the rows that exists in the table based on a condition. I'm looking at using CASE blocks!

这里是我所拥有的:

INSERT INTO MyTable (value1, value2) values
    (1, SELECT t.name,
          CASE WHEN t.name IN ('MyName') THEN 1
          ELSE 2
        END AS value2
       FROM MyTable t);

我得到一个错误:

ERROR: syntax error at or near "select"
SQL state: 42601
Character: 71

有什么线索吗?

推荐答案

好的,这是插入查询固定语法

OK, this is the insert query with the syntax fixed

 INSERT INTO MyTable (value1, value2) 
        SELECT t.name,
              CASE WHEN t.name IN ('MyName') THEN 1
              ELSE 2
            END AS value2
           FROM MyTable;

如果要更改现有行,则需要更新查询,例如

If you're trying to change existing rows, you need an update query, e.g.

-- first update, set value1 to 1 and value2 for all rows
UPDATE MyTable set value1 = 1,value2 = 2;

-- next query. Set value2 = 1 for only those rows matching your criteria
 UPDATE MyTable
    SET value2 = 1 WHERE name IN ('MyName');

这篇关于插入中的Postgres CASE语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆