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

使用Knex的.withRecursive执行递归查询抛出SELECT*无表错误如何解决

问题原因

你直接将knex.raw作为withRecursive的第二个参数时,Knex的SQL生成逻辑会额外拼接无效的查询片段,最终生成的语句出现了无对应表的SELECT *部分,因此触发报错。

解决方案

有两种常用修改方式可解决该问题:

方案1:使用查询构建器嵌套raw(推荐,兼容性最好)

client
    .withRecursive('childs', (qb) => {
        qb.select(knex.raw(
            `id, ARRAY[id] as path, false as cycle FROM taxonomy WHERE taxonomy.id = ?
            UNION
            SELECT T.id, path || T.id, T.id = ANY(path) FROM taxonomy T INNER JOIN childs C ON C.id = T.parent_id AND NOT cycle`,
            [4]
        ))
    })
    .select('id')
    .from('childs')

方案2:完全用Knex查询语法重构,避免硬编码SQL

client
    .withRecursive('childs', (qb) => {
        qb.select(
                'id',
                knex.raw('ARRAY[id] as path'),
                knex.raw('false as cycle')
            )
            .from('taxonomy')
            .where('id', 4)
            .union((unionQb) => {
                unionQb.select(
                        'T.id',
                        knex.raw('path || T.id'),
                        knex.raw('T.id = ANY(path)')
                    )
                    .from('taxonomy as T')
                    .innerJoin('childs as C', 'C.id', 'T.parent_id')
                    .where('cycle', false)
            })
    })
    .select('id')
    .from('childs')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:51:02