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

Postgres多对多关系下如何查询匹配的单条关联宠物记录

问题解决方法

错误原因

你当前的查询JOIN关联条件不完整,仅指定了宠物ID匹配,没有建立中间表pet_petowner和pet表的主键关联,导致只要pet_petowner表中存在任意一条符合owner_id条件的记录,就会返回指定ID的宠物数据,和两者是否存在绑定关系无关。
同时原有代码直接拼接SQL参数存在严重的SQL注入风险,需要改用参数化查询修复。

修正后的查询语句

SELECT pet.id as id, pet.first_name as first_name, pet.last_name as last_name
FROM pet_petowner owner_pet
-- 先关联中间表和宠物表的主键,保证数据对应
JOIN pet pet ON owner_pet.pet_id = pet.id
-- 同时过滤用户ID和宠物ID,仅存在绑定关系时返回数据
WHERE owner_pet.owner_id = $1 AND owner_pet.pet_id = $2;

修正后的Express代码

exports.getPet = async (req, res) => {
  const query = `SELECT pet.id as id, pet.first_name as first_name, pet.last_name as last_name
                 FROM pet_petowner owner_pet 
                 JOIN pet pet ON owner_pet.pet_id = pet.id
                 WHERE owner_pet.owner_id = $1 AND owner_pet.pet_id = $2`;
  // 使用参数化查询传入参数,避免SQL注入
  const { rows } = await pool.query(query, [req.params.owner_id, req.params.pet_id]);
  // 无匹配数据时返回404更符合接口规范
  if (!rows.length) {
    return res.status(404).send({ msg: "未查询到对应宠物信息" });
  }
  res.status(200).send(rows[0]);
};

内容的提问来源于stack exchange,提问作者The silent one

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 10:45:03