简体   繁体   English

使用可选参数运行 LIKE 查询 - SQLite3

[英]Run LIKE query with optional parameters - SQLite3

I'm creating an electron application that uses better-sqlite3 and I wanted to know, in general, if there was a way to run a query that uses LIKE with optional parameters?我正在创建一个使用better-sqlite3的 electron 应用程序,我想知道,一般来说,是否有一种方法可以运行使用LIKE和可选参数的查询? Let's say there's a table people that contains the columns firstname and lastname.假设有一个包含 firstname 和 lastname 列的 people 表。 A user could search by:用户可以通过以下方式搜索:

Firstname only in which case the query would be:只有名字,在这种情况下查询将是:

SELECT * from people WHERE firstname LIKE %userEnteredFname%

Lastname only in which case the query would be:仅姓氏,在这种情况下查询将是:

SELECT * from people WHERE lastname LIKE %userEnteredLname%

Or both fields:或两个字段:

SELECT * from people WHERE firstname LIKE %userEnteredFname% AND lastname LIKE %userEnterLname%

And just FYI, there's a way to INSERT with optional parameters:仅供参考,有一种INSERT可选参数的方法:

const stmt = db.prepare('INSERT INTO cats (name, age) VALUES (?, ?)');
const info = stmt.run('Joey'); //age would be null

The query depends on which search parameter is entered.查询取决于输入的搜索参数。 Sure enough you can prepare statements for a small number of input fields but I have about 7 and there can be a lot of combinations there.果然,您可以为少量输入字段准备语句,但我有大约 7 个,并且那里可以有很多组合。

As long as userEnterLname is an empty string,只要userEnterLname是一个空字符串,

 SELECT * from people WHERE firstname LIKE %userEnteredFname% AND lastname LIKE %userEnterLname%

is the same as是相同的

 SELECT * from people WHERE lastname LIKE %userEnteredLname%

So just keep the extra variables empty unless you want to search them.因此,除非您想搜索它们,否则只需将额外的变量保留为空。

The operator LIKE returns NULL when any of its operands is NULL .运算符LIKE在其任何操作数为NULL NULL
So for all the columns use COALESCE() which will return 1 (= TRUE ) in case the value passed is NULL :因此,对于所有列,使用COALESCE() ,如果传递的值为NULL ,它将返回1 (= TRUE ):

SELECT * 
FROM people 
WHERE COALESCE(firstname LIKE '%' || ? || '%', 1) 
  AND COALESCE(lastname LIKE '%' || ? || '%', 1)

The ? ? placeholders stand for the parameters that you will pass to the query.占位符代表您将传递给查询的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM