You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Knex在PostgreSQL中组合双字段实现单值匹配查询

在Knex中实现PostgreSQL双字段组合匹配查询

要实现将first_name和last_name组合成"last_name, first_name"格式并与目标值匹配,你需要使用Knex的.whereRaw()方法编写原生PostgreSQL字符串拼接逻辑——因为Knex的对象式where语法无法直接处理字段间的运算。

实现代码

假设你要匹配的目标全名是targetFullName(格式为"last_name, first_name"),修改你的查询代码如下:

const targetFullName = "Smith, Alice"; // 你的目标匹配值
const res = await Database.knex
  .select()
  .from(`${DB_SCHEMA}.t_contacts as contacts`)
  .where({
    'contacts.email': email,
    'contacts.status': 'ACTIVE'
  })
  // 使用PostgreSQL的concat函数拼接字段
  .whereRaw('concat(contacts.last_name, \', \', contacts.first_name) = ?', [targetFullName]);

可选方案:处理空值场景

如果需要忽略空字段(比如first_name为空时,只保留last_name),可以改用concat_ws函数(自动忽略空值):

.whereRaw('concat_ws(\', \', contacts.last_name, contacts.first_name) = ?', [targetFullName]);

关键说明

  • 使用.whereRaw()的原因:需要构造自定义的字段拼接逻辑,Knex的对象语法不支持这类字段运算。
  • 占位符?的作用:避免SQL注入风险,Knex会自动处理参数的转义。

内容的提问来源于stack exchange,提问作者Aleksandra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 14:38:13