如何在PostgreSQL和Node JS中进行类似搜索 [英] how to make a like search in postgresql and node js

查看:133
本文介绍了如何在PostgreSQL和Node JS中进行类似搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用节点js和用于连接到postrgresql的模块pg
i想要搜索标签数据库,但我无法使其工作,在变量标签中的
我保存了url的参数,但咨询不会返回任何结果。
我该如何解决?

I am using node js and the module pg for connect to postrgresql i want to make a search for a database of tags but i can't make it work, in the variable tag i saved the param of the url , but the consult doesn't return any results. how can i fix?

app.get("/tags", function(req, res){
        var tag = req.query.q;
        res.json(tag)
        var search = db.client.query("SELECT * FROM tags WHERE name LIKE '%$1%'", [tag], function(err, result){
                res.json(result);
            }
        );
    });


推荐答案

我不知道node.js PostgreSQL接口很好,但我认为我可以看到问题所在。这是一个SQL字符串文字,其中包含带编号的占位符:

I don't know the node.js PostgreSQL interface that well but I think I can see the problem. This is an SQL string literal that contains a numbered placeholder:

'%$1%'

该字符串中的 $ 1 不会替换为 tag 因为字符串中的占位符根本不是占位符,它们只是恰好具有与占位符相同形式的子字符串。

The $1 inside that string won't be replaced with the value of tag because placeholders inside strings are not placeholders at all, they're just substrings that happen to have the same form as a placeholder.

两个常用选项是:


  1. 在客户端添加通配符代码。

  2. 通配符连接到数据库内的字符串上。

  1. Add the % wildcards in the client code.
  2. Concatenate the % wildcards onto the strings inside the database.

第一个看起来像这样:

db.client.query("SELECT * FROM tags WHERE name LIKE $1", ['%' + tag + '%'], ...

,第二个是这样的:

db.client.query("SELECT * FROM tags WHERE name LIKE '%' || $1 || '%'", [tag], ...

使用您所使用的任何一种方法喜欢。

Use whichever approach you prefer.

这篇关于如何在PostgreSQL和Node JS中进行类似搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆