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
相关产品推荐
相关产品推荐

