合并两列并对结果执行 where 操作
Combine two columns and perform a where operation on the result
我有两列,一列用于 'firstName',一列用于 'lastName'。我正在尝试对这两列的串联执行 where 操作以匹配全名。
这是我试过的方法:
select * from table where concat_ws(' ', 'firstName', 'lastName') like '%some_value%'
这只是 return 一个空白数组。
示例数据:
firstName
lastName
Clayton
Smith
Barbara
Clayman
Sam
Peterson
当some_value =粘土时,应该return'Clayton Smith'和'Barbara Clayman'
我从其他一些 Whosebug 答案中得到了很多这种语法,这些答案被标记为类似问题的解决方案,但是当我自己实现这个时,我无法让它工作。
FWIW 我将使用 knex.js 构建这些查询,因此如果有 knex.js 特定的解决方案,请随时回答。
使用STR_POS
PostgreSQL strpos() 函数用于查找子字符串在字符串中匹配的位置。
select * from table where strpos(concat_ws(' ', first_name, last_name),'Clay') > 0
用变量替换文字
您的 CONCAT_WS
调用的参数应该用双引号引起来。如果它们在单引号中,Postgres 会将它们解释为字符串文字。这应该有效:
SELECT * FROM table WHERE CONCAT_WS(' ', "firstName", "lastName") ILIKE '%some_value%'
我还建议使用 ILIKE
而不是 LIKE
- 这将使您的搜索词的模式匹配不区分大小写。
我有两列,一列用于 'firstName',一列用于 'lastName'。我正在尝试对这两列的串联执行 where 操作以匹配全名。
这是我试过的方法:
select * from table where concat_ws(' ', 'firstName', 'lastName') like '%some_value%'
这只是 return 一个空白数组。
示例数据:
firstName | lastName |
---|---|
Clayton | Smith |
Barbara | Clayman |
Sam | Peterson |
当some_value =粘土时,应该return'Clayton Smith'和'Barbara Clayman'
我从其他一些 Whosebug 答案中得到了很多这种语法,这些答案被标记为类似问题的解决方案,但是当我自己实现这个时,我无法让它工作。
FWIW 我将使用 knex.js 构建这些查询,因此如果有 knex.js 特定的解决方案,请随时回答。
使用STR_POS
PostgreSQL strpos() 函数用于查找子字符串在字符串中匹配的位置。
select * from table where strpos(concat_ws(' ', first_name, last_name),'Clay') > 0
用变量替换文字
您的 CONCAT_WS
调用的参数应该用双引号引起来。如果它们在单引号中,Postgres 会将它们解释为字符串文字。这应该有效:
SELECT * FROM table WHERE CONCAT_WS(' ', "firstName", "lastName") ILIKE '%some_value%'
我还建议使用 ILIKE
而不是 LIKE
- 这将使您的搜索词的模式匹配不区分大小写。