表名称:客户
customer_id Profiles dept_code
------------------------------------------
3361 ,15,31,4, ,01,02,
3362 ,32, ,01,03,
3363 ,04,
3364 ,1,20,21, ,01,02,03,
表名称:customers_backup
customer_id Profiles dept_code
--------------------------------------
3361 ,15,31,4, ,01,02,
3362 ,32,33,34, ,01,03,
3363 ,10, ,04,
3364 ,1,20,21, ,01,02,03,
我试图更新客户表的配置文件,并在下面给出条件,
1(如果客户配置文件为null => UPDATE customer_backup配置文件
2(如果客户配置文件等于customers_backup profile =>只要保持客户 轮廓3(如果客户配置文件<> to cunitess_backup profile =>保留客户配置文件并附加不在客户表中的customeres_backup的个人资料。
我需要以下输出:
表名称:客户
customer_id Profiles dept_code
------------------------------------------------
3361 ,15,31,4, ,01,02,
3362 ,32,33,34, ,01,03, ( How to apply this condition?)
3363 ,10, ,04,
3364 ,1,20,21, ,01,02,03,
以下是我为条件1&2.但是他们没有给出预期的结果。
update customers set profiles=
CASE WHEN (select unnest(array[customers.profiles])) is null
THEN customers_backup.profiles
WHEN (select unnest(array[customers.profiles])) =
(select unnest(array[customers_backup.profiles]))
THEN customers.profiles
WHEN (select unnest(array[customers.profiles])) <>
(select unnest(array[customers_backup.profiles])) --- Need help here
THEN user_enrollment_backup1.profiles
END FROM customers_backup
WHERE customers_backup.customer_id=customers.customer_id
AND customers_backup.dept_code= customers.dept_code;
有人可以帮忙吗?预先感谢。
如果要使用实际数组,则需要先清理数据,以便以正确的格式 - 即没有前导/尾随逗号。一旦拥有此功能,就可以将profiles
字段作为数组数据类型施放并使用数组串联,类似于以下方式:
SELECT
ARRAY(SELECT DISTINCT UNNEST(customers.profiles || customers_backup.profiles))
FROM ...
这应该将您的数组元素组合到一个数组中,然后unnest&amp;删除重复元素,然后最终将其重新组合回最终数组。我认为他们不会被订购,但这应该让您入门。
看来您的profile
值不是真实数组,因此您需要将它们作为上述查询中的数组铸造。
您可以使用UPDATE
表FROM
语法。请注意,可以使用=
和<>
运算符比较数组。仅用于查找联盟(第三种情况(,您可以使用UNNEST
。
UPDATE customers AS c
SET profiles = CASE WHEN c.profiles IS NULL
THEN cb.profiles
WHEN array[c.profiles] = array[cb.profiles]
THEN c.profiles
WHEN array[c.profiles] <> array[cb.profiles]
THEN ( select string_agg(a,'')
from (
select distinct
unnest(array[RTRIM(c.profiles,',')::VARCHAR] || array[cb.profiles]) as a
) s
)
END
FROM customers_backup as cb
WHERE c.customer_id = cb.customer_id;
还要注意,如果您create extension intarray,
,则可以使用简单|数组工会的操作员。
demo