使用Knex操作PostgreSQL时出现id列引用歧义报错是什么原因?
问题原因及修复方案
- 导致
id字段歧义报错的直接原因:你定义的fieldActiveComplaints数组中,第一个字段直接写了id,但关联的mailbox_complaints和superheroes两张表都存在id字段,数据库无法判断需要取哪张表的id,因此抛出该错误。修复时只需给id加上对应表前缀即可,也可以额外加别名方便后续使用,比如需要取投诉表的id就写为mailbox_complaints.id as complaint_id,需要取超级英雄表的id就写为superheroes.id as superhero_id。 - 计数查询存在语法错误:你写的count查询中
from('superheroes')之后又关联了同一张superheroes表,而查询需要用到的mailbox_complaints没有出现在from或关联列表中,执行时会额外抛出表不存在的错误,需要把count查询的from对象改为mailbox_complaints和主查询保持一致。 - 可选优化:你当前的
where('superheroes.id', '=', 'mailbox_complaints.id')条件和join关联逻辑冲突,join已经通过superheroes.id = mailbox_complaints.superheroe_id做好了表关联,该where条件会强制要求超级英雄id和投诉id相等,不符合正常业务逻辑,确认不需要可以直接删掉。
修复后的代码示例
字段定义:
const fieldActiveComplaints = [ 'mailbox_complaints.id as complaint_id', // 明确指定表归属,避免歧义 'superheroes.name', 'mailbox_complaints.commentary', // 其他字段也建议加表前缀,避免后续新增字段重复 'mailbox_complaints.created_date', ]
查询逻辑:
let activeComplaints = await knex.select(fieldActiveComplaints) .from('mailbox_complaints') .innerJoin('superheroes', 'superheroes.id', 'mailbox_complaints.superheroe_id') .orderBy('mailbox_complaints.id', 'desc') .limit(pageSize) .offset(offset) let count = knex.count() .from('mailbox_complaints') .innerJoin('superheroes', 'superheroes.id', 'mailbox_complaints.superheroe_id') .then(([query]) => parseInt(query.count, 10)) console.log('activeComplaints==>', activeComplaints) return Promise.all([activeComplaints, count])
内容的提问来源于stack exchange,提问作者Jesus Favela
相关产品推荐
相关产品推荐

