查询以在多个列中搜索单个值

时间:2019-07-25 04:44:16

标签: sql postgresql

我正在尝试为我的应用添加搜索功能,希望它能够搜索名称或描述可能与搜索值匹配的任何项目。

我的专栏是标题,描述,sku等。

因此,如果有人搜索“绿色”,则可能会返回标题为“绿色杯子”的商品,并且会返回另一个描述为“纯绿色微光板”的商品

var data = "green"
client.query('SELECT * FROM items WHERE $1 IN (upc, title, description)', [data], function(err, res){
   //return res.rows; 
}

有没有办法做到这一点?

编辑:这是我的全部功能

exports.getItems = function(data, cb) {
  var client = new Client(url);
  client.connect();
  client.query('SELECT DISTINCT title, description, sku FROM items WHERE title + description + sku LIKE  %'+data+'%',  (err, res) => {
    if (err) throw err;
    if (res.rows.length === 0) {
      console.log("test");
      client.end();
      return cb(null, null);
    }
    console.log(res.rows);
    //cb(null, res.rows[0]);
    client.end();
  });
};

4 个答案:

答案 0 :(得分:1)

对于不区分大小写的用户,您可以执行ILIKE

SELECT      *
FROM        items
WHERE       (upc ILIKE '%search_string%')
            OR (title ILIKE '%search_string%')
            OR (description ILIKE '%search_string%');

这回答了您的问题,但是您会发现它很慢。

加快速度的方法是创建一个名为“ search_string”的列,其中将您要搜索的所有列加在一起,然后在其上构建GIN索引。然后,您可以在此处搜索值。

答案 1 :(得分:0)

   SELECT DISTINCT title, description, sku FROM items 
       WHERE
       title LIKE '%green%' OR
       description LIKE '%green%' OR
       sku LIKE '%green%'

您不想使用SELECT * FROM items,因为如果多个列符合您的条件,您将得到重复项。

答案 2 :(得分:0)

这是更少的代码:)

POSTGRESQL

var data = "green"
client.query("SELECT DISTINCT title, description, sku FROM items WHERE title || description || sku LIKE $1", ['%'+data+'%'], function(err, res){
   //return res.rows; 
}

答案 3 :(得分:0)

如果您只想提供一次搜索字符串,则可以使用稍微复杂一点的查询来做到这一点:

select *
from data
where exists (select *
              from unnest(array[title, description, upc]) t(c)
              where t.c ilike '%green%');

当然'%green%'也可以是参数。

如果要添加要搜索的其他列,只需将它们添加到数组中。

但是,这很快,并且也无法建立索引。如果性能至关重要,请考虑Joseph Lee的答案,并在每列上创建一个trigram index

或者甚至考虑使用full text search-但这取决于您要搜索的内容和搜索方式的确切要求。 FTS通常不能很好地替代LIKE查询。