如何在不进行硬编码的情况下在 SIMILAR TO 中使用多个值

How to use multiple values in SIMILAR TO without hardcoding

我有一列如下(虚数):

<table_name>.<column_name>
a_b
g_c
w_d
k_e

我想使用 SIMILAR TO 运算符将此列与另一列匹配。类似于:

Select *
from <table_name1>
where column_name1 SIMILAR TO '%(<table_name>.<column_name>)%';

我知道 SIMILAR TO 中的多个值需要用管道运算符分隔。但是我不知道该怎么做。

如有任何帮助,我们将不胜感激。

EDIT:我需要 JOIN 这两个表,因为我需要其中一列 group。有什么好的方法吗?

我想你要找的是

SELECT t2.*
FROM table2 t2
WHERE t2.column1 similar to '%('||(SELECT LISTAGG(t1.column1, '|') FROM table1 t1)||')%'

请注意,我对 Redshift 使用 listagg,但在 Postgre 中它将是 string_agg

listagg/string_agg 会将所有值(第一个参数)连接在一起,用竖线(第二个参数)分隔。所以 '%('||(SELECT LISTAGG(t1.column1, '|') FROM table1 t1)||')%' 会产生一个像 %(a_b|g_c|w_d|k_e)% 这样的字符串,这就是你想要的 similar to 比较。

要考虑的替代方案(特别是如果您匹配的值可能超过 64K 个字符并导致 listagg 出现问题)可能是

SELECT distinct t2.* -- Distinct because a row in t2 might match multiple rows in t1
FROM table2 t2 INNER JOIN table1 t1
 on t2.column1 similar to '%('||t1.column1||')%' -- This could just be a normal like if you don't have any special regex besides percent and underscore