postgresql - 在 A 列中搜索 B 列中的字符串匹配项

标签 postgresql search

使用 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/

相关文章:

javascript - Intellij 找不到 .js 文件(类搜索)

javascript - jQuery 搜索元素中的文本作为 SQL 查询 LIKE?

Azure 搜索突出显示不仅匹配 Lucene 字段范围查询中使用的字段

java - 等于和包含有什么区别

c++ - Incomplete parameter error Including postgres.cpp working file in other .cpp 文件

python - 使用 Python 变量更新 PostgreSql 表

sql - 使用 postgres 创建连续的证书编号

sql - 使用 CASE WHEN 子句的百分比差异

sql - 如何找到总数

javascript - 根据项目属性值在数组中查找某些项目的最佳方法是什么?