aws redshift if else逻辑

up9lanfz  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(402)

我基本上想在redshift中做以下事情,但由于redshift不支持程序性语句,我不确定如何实现我的目标:

IF EXISTS (select username,accountnumber from table where username={1})
THEN
    IF {0} NOT IN accountnumber 
        update table set accountnumber = 
        accountnumber+=',{0}' where username='{1}'
    END IF
ELSE
    insert into table values({1},{0});
END IF

参数1是用户id,参数2是用户名
在红移中实现这一点的最佳方法是什么?谢谢你的帮助
跑步:

CREATE TABLE IF NOT EXISTS table (account_number 
varchar(100), username varchar(50));
case when true
update table set accountnumber = accountnumber+=',{0}' 
where username='{1}'
else insert into table values ('{0}','{1}')
end

定义true只是为了演示。我得到以下错误:

---> syntax error at or near "case"
LINE 2: case when 1=1
vkc1a9a2

vkc1a9a21#

我看到红移支持 exists 所以也许这会管用

/* if the row is there it'll update it. If not it won't */
UPDATE Table Set Field='NewValue' Where KeyValue=1

/* if the row is not there it'll insert it */
INSERT INTO Table (KeyValue,Field1,Field2)
SELECT 1,'NewValue','NewValue'
WHERE NOT EXISTS (SELECT * FROM Table WHERE KeyValue=1)
jfewjypa

jfewjypa2#

你需要使用 CASE 类似于 if-else .

case when new_record = existing_record
update existing_record
else insert new_record
end
unftdfkk

unftdfkk3#

如果我没弄错的话,看来你是在试图做一个升级。你能在红移上使用合并功能吗?在执行插入/更新之前,需要使用一个临时表来保存一些值。
下面是红移文档中的一些示例
https://docs.aws.amazon.com/redshift/latest/dg/merge-examples.html

相关问题