使用 PostgreSQL,如何在 A 列中搜索 B 列中的字符串匹配项?
中间表(子查询)输出:
string_a_id | string_a | string_b_id | string_b
-----------------------------------------------
1 'hello world' 11 null
2 'hello world' 13 null
3 'ipsum lorem' 21 'hello world'
正在查询上面的中间表以进行匹配。 预期输出:
string_a_id | string_a | string_b_id | string_b
-----------------------------------------------
1 'hello world' 21 'hello world'
2 'hello world' 21 'hello world'
我正在使用
select *
from (
// subquery
) as subquery_results
where (trim(subquery_results.string_a) ilike trim(subquery_results.string_b))
但这会返回 0 个结果。
最佳答案
当你想将每个 string_a
与任何 string_b
进行比较时,你应该使用自连接:
with dataset(string_a_id, string_a, string_b_id, string_b) as (
values
(1, 'hello world', 11, null),
(2, 'hello world', 13, null),
(3, 'ipsum lorem', 21, 'hello world')
)
select q1.string_a_id, q1.string_a, q2.string_b_id, q2.string_b
from dataset q1
join dataset q2 on trim(q1.string_a) ilike trim(q2.string_b)
string_a_id | string_a | string_b_id | string_b
-------------+-------------+-------------+-------------
1 | hello world | 21 | hello world
2 | hello world | 21 | hello world
(2 rows)
将初始查询中的 values
替换为您的实际查询。
关于postgresql - 在 A 列中搜索 B 列中的字符串匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54229667/