在两列中搜索完整的字符串或子字符串

时间:2014-10-22 14:18:47

标签: java sql postgresql ormlite

我有2列(产品名称和说明)并尝试创建搜索。例如:

表“产品”:

id   name             description
---------------------------------
1    Inspiron 7720    Intel i7
2    Inspiron 7720    Intel i5
3    Inspiron 5720    Intel i7
4    Asus Zenbook     Intel i5

并在搜索栏中 - “Inspiron 5720 i7”。

我如何得到结果:
1)id = 3 Inspiron 5720(完全巧合)
2)id = 1 Inspiron 7720(部分巧合)
3)id = 2 Inspiron 7720(部分巧合)

我可以使用这样的东西:

"SELECT * FROM product WHERE LOWER( product.product_name ) LIKE  '%"
                + searchString + "%'" +
                " OR LOWER( product.product_description ) LIKE  '%"
                + searchString + "%'"

但我相信,这是最明确的解决方案。

2 个答案:

答案 0 :(得分:0)

除了使用准备好的陈述外,您还可以查看FREETEXT是否符合您的需求:

PreparedStatement pstmt = con.prepareStatement(
  "SELECT * FROM product 
  WHERE FREETEXT(product.product_name + ' ' + product.product_description, ? )");

pstmt.setString(1, searchString);

== EDIT ==

尝试使用ORDER BY结合SOUNDEX

按相似性排序结果
PreparedStatement pstmt = con.prepareStatement(
  "SELECT * FROM product 
  WHERE FREETEXT(product.product_name + ' ' + product.product_description, ? )
  ORDER BY 
    ABS(SOUNDEX(product.product_name + ' ' + product.product_description)
      -SOUNDEX(?)) ")

答案 1 :(得分:0)

您可以使用给定的单个单词构建查询,计算匹配项并与单词数进行比较。

select
  id,
  name,
  case 
    when score = 3 then 'full coincidence'
    else 'partial coincidence'
  end as match
from
(
  select id,
    case when name like '%Inspiron%' or description like '%Inspiron%' then 1 else 0 end +
    case when name like '%5720%' or description like '%5720%' then 1 else 0 end +
    case when name like '%i7%' or description like '%i7%' then 1 else 0 end as score
  from mytable
)
where score > 0
order by score desc;

编辑:为了获得更好的结果,您可以按照自己的建议使用LOWER,并添加空白以查找整个单词。

name like '%Inspiron%'

变为

lower(' ' + name + ' ') like '% inspiron %'