【问题标题】:Searching substring in PostgreSQL (part II)在 PostgreSQL 中搜索子字符串(第二部分)
【发布时间】:2014-08-17 18:31:05
【问题描述】:

我找到了这个 query

CREATE TABLE tableA (string_a text);
INSERT INTO tableA(string_a) VALUES 
('the manual is great'), ('Chicken chicken chicken'), ('bork');

CREATE TABLE tableB(candidate_str text);
INSERT INTO tableB(candidate_str) VALUES
('man'),('great'),('chicken');

SELECT string_a 
FROM tableA 
WHERE string_a LIKE ANY (SELECT '%'||candidate_str||'%' FROM tableB);

结果:

the manual is great
chicken chicken chicken

问题: 怎么做才能有这个新结果?

the manuel is great      | great
chicken chicken chicken  | chicken

【问题讨论】:

  • 如果有多个匹配项,请定义从tableB 中选择的哪个行。另外,您希望每行匹配 few 还是 many

标签: sql postgresql substring


【解决方案1】:

使用 JOIN:

SELECT a.string_a, b.candidate_str
FROM tableA a
  JOIN tableB b ON a.string_a LIKE '%'||b.candidate_str||'%';

请注意,这将显示带有the manual is great 的行两次,因为candidate_strmanual 中的man 和单词great 匹配。这可以通过例如改变使用distinct on 只返回来自tableA 的行一次。

【讨论】:

  • 请注意,您将前 通配符与 LIKE 一起使用。这将破坏任何索引的使用,这是一个坏主意。为什么不为此使用 PostgreSQL 的全文搜索功能呢?
  • @Timusan:这是一个有效的观点,但您应该向 leasye Btw 指出这一点:在 Postgres 中有 is 索引类型可以与这样的 LIKE 条件一起使用: depesz.com/2011/02/19/waiting-for-9-1-faster-likeilike
  • @a_horse_with_no_name:啊,抱歉,一定还在睡觉,在原始查询中没有看到通配符。嗯,这种索引类型对我来说确实是新闻(感谢提醒),听起来很诱人,但在 Leeasye 的情况下仍然更喜欢 FTS。
猜你喜欢
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 1970-01-01
  • 2021-06-28
  • 2012-08-16
  • 2012-06-04
  • 2018-01-07
  • 1970-01-01
相关资源
最近更新 更多