【问题标题】:substring match on both tables of a join连接的两个表上的子字符串匹配
【发布时间】:2018-05-01 06:02:54
【问题描述】:

如何将一个子字符串匹配到另一个子字符串。我似乎只能ilike 搜索其中一个,不能同时搜索子字符串。

给定表格:

对话

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 || '%');

两个模糊的ilike 匹配OR

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

两个输出:

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

【问题讨论】:

  • his name is / my name is
  • 为了强调蒂姆的评论,“他的名字是”不匹配“我的名字是”,所以你不能做匹配。时期。您需要更加认真地思考您的数据以及您想要完成的任务。

标签: sql postgresql join substring


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    首先执行笛卡尔积,以 WHERE 子句为限制,看看您可以期待什么样的结果。

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

    我认为您的左连接尝试不匹配任何内容,因为 ILIKE 语句的左侧有通配符。这些是,afaik,从字面上理解。此外,使用“AND”进行连接:您想要两个谓词都为真的对。交叉连接在这里很合适,因为您非常严格地定义了 where 子句。

    左连接仅用于您想要绝对获得“对话”的地方,并且可以选择连接“结构”。在这种情况下,请执行“完全连接”,这样您就可以准确地看到进行了哪些匹配。稍后,您可以决定进一步过滤掉所有内容,并将 where 子句谓词放入合适的 join 子句中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      相关资源
      最近更新 更多