连接的两个表上的子字符串匹配

时间:2018-05-01 06:02:54

标签: sql postgresql join substring

如何在子字符串匹配上对另一个子字符串执行连接。我似乎只能ilike搜索其中一个,而不是搜索子字符串。

给出表格:

DIALOG

string             
-------------------
Hi, my name is dan

结构

structure
----------
his name is / my name is
hello, my / you are
how are you?

预期输出

string              | structure
-------------------------------
Hi, my name is dan  | his name is / my name is

尝试:

两个ilike模糊匹配:

select string, structure from dialog left join structures on ('%' || string || '%' ilike '%' || structure || '%');

两个模糊ilikeOR匹配:

select string, structure from dialog left join structures on (string ilike '%' || structure || '%') or (structure ilike '%' || string || '%');

两个输出:

string              | structure
-------------------------------
Hi, my name is dan  |

2 个答案:

答案 0 :(得分:1)

如果结构实际匹配,则可以使用正则表达式:

select string, structure
from dialog d left join
     structures s
     on string ~ replace(string, ' / ', '|');

当然,这不适用于示例数据,因为字符串实际上并不匹配。

这也表明你的结构实际上应该是一个正则表达式。

答案 1 :(得分:0)

首先执行笛卡尔积,限制WHERE子句,以查看您可以期望的结果类型。

select string, structure from dialog CROSS join structures WHERE string ilike '%' || structure || '%' AND structure ilike '%' || string || '%'

我认为你的左连接尝试与任何事情都不匹配,因为ILIKE语句左侧有通配符。从字面上看,这些是afaik。另外,使用' AND'对于连接:你想要两个谓词都正确的夫妻。交叉连接在这里适合,因为你非常紧密地定义了where子句。

左连接仅用于您希望绝对获得“对话框”的位置,可选择使用“#”结构'连接到它。在这种情况下,请执行“完全加入”,这样您就可以确切地看到匹配的匹配类型。稍后,您可以决定进一步过滤掉所有内容,并将where子句谓词放在合适的join子句中。

相关问题