在node-postgres中使用子查询作为值时遭遇UUID语法错误
问题原因
你当前的写法是把(select id from another_table limit 1)作为字符串参数传给$2,PostgreSQL会将其当作普通字符串值去匹配uuid类型的field2,自然会触发格式错误——因为这个字符串本身并非合法的uuid格式。
解决方法
参数化查询的参数仅支持传入静态值,无法传入SQL语句片段。要实现插入子查询结果的需求,直接将子查询写入SQL语句即可:
pg.query(`insert into tbl (field1, field2) values($1, (select id from another_table limit 1))`, ["a"])
如果子查询的逻辑需要动态调整(比如表名、过滤条件),可以进行SQL拼接,但必须注意防范SQL注入,可使用pg自带的标识符转义方法:
const targetTable = 'another_table'; pg.query(`insert into tbl (field1, field2) values($1, (select id from ${pg.escapeIdentifier(targetTable)} limit 1))`, ["a"])
内容的提问来源于stack exchange,提问作者Sherif eldeeb
相关产品推荐
相关产品推荐

