如何将含子查询IN语句的SQL转换为TypeORM实现?
将SQL查询转换为TypeORM实现(含IN子查询)
问题描述
我有一段简单的SQL查询语句:
select * from comments c inner join users u on u.id = c.user_id where user_id = 1 OR (c.user_id IN (select user_id_one from friends f where user_id_two = 1))在将其转换为TypeORM实现时,我遇到了很大的困难,尤其是其中的
c.user_id IN (select user_id_one from friends f where user_id_two = 1)这部分,不清楚如何在TypeORM中结合使用IN运算符与子查询语句。
解决方案
TypeORM的QueryBuilder可以完美适配这类包含子查询的复杂查询,下面是对应实现:
1. 构建子查询
先创建获取目标用户好友ID的子查询,对应原SQL中的子查询部分:
// 假设Friends是对应friends表的实体类 const friendSubQuery = getConnection() .createQueryBuilder() .select("f.user_id_one") .from(Friends, "f") .where("f.user_id_two = :userId", { userId: 1 });
2. 构建主查询(关联+条件)
通过QueryBuilder实现主查询的关联和OR条件,直接将子查询嵌入IN运算符中:
// 假设Comment是对应comments表的实体类,且Comment实体与User实体存在关联(user字段对应users表) const comments = await getConnection() .createQueryBuilder(Comment, "c") .innerJoinAndSelect("c.user", "u") // 对应原SQL的inner join users u on u.id = c.user_id .where("c.user_id = :userId", { userId: 1 }) // 直接嵌入子查询到IN条件中 .orWhere("c.user_id IN (" + friendSubQuery.getQuery() + ")", friendSubQuery.getParameters()) .getMany();
关键说明
- 确保实体类(
Comment、User、Friends)已正确配置数据库表映射和关联关系 - 这种方式无需提前执行子查询,TypeORM会将其编译为和原SQL一致的原生查询,性能更优
- 如果使用Repository实例,也可以通过
commentRepository.createQueryBuilder("c")替代getConnection().createQueryBuilder(Comment, "c"),逻辑完全一致
内容的提问来源于stack exchange,提问作者joethemow
相关产品推荐
相关产品推荐

