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

Kysely(Postgres)中含Raw SQL的多表FROM写法报错求助

问题解决:Kysely实现Postgres交叉连接(FROM X, Y)的语法错误修复

你的代码报错核心原因是SQL模板字符串里多了多余的左括号且未闭合,同时遗漏了原SQL中的WHERE条件。以下是修正后的实现:

错误点分析

  1. 你在sql模板字符串里写了(jsonb_array_elements(...),多了一个前导左括号,且没有对应的闭合括号,直接导致Postgres语法解析失败。
  2. 原SQL中的where cast(value as integer)=2条件没有在Kysely代码中实现,需要补充。

修正后的代码

const res2 = await db
  .selectFrom([
    'products',
    sql<{ value: number }>`jsonb_array_elements(products.properties#>'{someProperty}')`.as('search_item')
  ])
  .select(['products.properties', 'search_item.value'])
  .where(sql`cast(search_item.value as integer) = 2`)
  .execute();

关键说明

  • 移除了jsonb_array_elements前多余的左括号,保持和原SQL一致的函数调用格式。
  • 明确指定sql的类型为{ value: number },对应jsonb_array_elements返回的value字段。
  • 在select中明确引用search_item.value(原SQL的value实际是search_item的字段)。
  • 通过where方法添加原SQL中的类型转换和条件判断,确保逻辑完整。

如果需要用Kysely的类型安全API替代原生SQL片段,也可以这样写(更符合Kysely风格):

const res2 = await db
  .selectFrom([
    'products',
    sql<{ value: number }>`jsonb_array_elements(products.properties#>'{someProperty}')`.as('search_item')
  ])
  .select(['products.properties', 'search_item.value'])
  .where(cast('search_item.value', 'integer'), '=', 2)
  .execute();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 11:42:35