如何在Amazon Redshift中验证c_1值是否在c_2的逗号分隔字符串中?
解决方案
你遇到的错误是因为ANY操作符要求右侧必须是数组类型,而你的c_2是逗号分隔的字符串(varchar),并非数组。针对Amazon Redshift环境,提供两种可行方案:
方案1:将字符串转为整数数组后匹配
利用Redshift的string_to_array函数将逗号分隔的c_2转换为整数数组,再使用ANY进行匹配:
select user_id, c_1, c_2, case when c_1 = any(string_to_array(c_2, ',')::int[]) then 1 else 0 end as c_1_is_in_c_2 from your_table;
- 说明:
string_to_array(c_2, ',')将字符串按逗号分割成文本数组,::int[]将其转换为整数数组,确保与c_1的整数类型匹配。
方案2:字符串边界匹配法
通过给c_2前后添加逗号,避免部分值匹配的问题(比如c_1=1时,不会误匹配c_2中的11):
select user_id, c_1, c_2, case when ',' || c_2 || ',' like '%,' || c_1 || ',%' then 1 else 0 end as c_1_is_in_c_2 from your_table;
- 注意:如果
c_2中的元素包含空格(比如listagg生成时带有空格),需要先清理空格,可修改为:
case when ',' || replace(c_2, ' ', '') || ',' like '%,' || c_1 || ',%' then 1 else 0 end
内容的提问来源于stack exchange,提问作者dmenesesg
相关产品推荐
相关产品推荐

