how to make a like search in postgresql and node js

后端 未结 2 681
庸人自扰
庸人自扰 2021-01-11 11:37

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 par

2条回答
  •  借酒劲吻你
    2021-01-11 12:44

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

    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.

    The two usual options are:

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

    The first one would look like this:

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

    and the second like this:

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

    Use whichever approach you prefer.

提交回复
热议问题