使用子查询

你可以轻松创建子查询。 FROMWHEREJOIN表达式都支持子查询。例如:

  1. const qb = await getRepository(Post).createQueryBuilder("post");
  2. const posts = qb
  3. .where(
  4. "post.title IN " +
  5. qb
  6. .subQuery()
  7. .select("user.name")
  8. .from(User, "user")
  9. .where("user.registered = :registered")
  10. .getQuery()
  11. )
  12. .setParameter("registered", true)
  13. .getMany();

使用更优雅的方式来做同样的事情:

  1. const posts = await connection
  2. .getRepository(Post)
  3. .createQueryBuilder("post")
  4. .where(qb => {
  5. const subQuery = qb
  6. .subQuery()
  7. .select("user.name")
  8. .from(User, "user")
  9. .where("user.registered = :registered")
  10. .getQuery();
  11. return "post.title IN " + subQuery;
  12. })
  13. .setParameter("registered", true)
  14. .getMany();

或者,你可以创建单独的查询构建器并使用其生成的 SQL:

  1. const userQb = await connection
  2. .getRepository(User)
  3. .createQueryBuilder("user")
  4. .select("user.name")
  5. .where("user.registered = :registered", { registered: true });
  6. const posts = await connection
  7. .getRepository(Post)
  8. .createQueryBuilder("post")
  9. .where("post.title IN (" + userQb.getQuery() + ")")
  10. .setParameters(userQb.getParameters())
  11. .getMany();

你可以在FROM中创建子查询,如下所示:

  1. const userQb = await connection
  2. .getRepository(User)
  3. .createQueryBuilder("user")
  4. .select("user.name", "name")
  5. .where("user.registered = :registered", { registered: true });
  6. const posts = await connection
  7. .createQueryBuilder()
  8. .select("user.name", "name")
  9. .from("(" + userQb.getQuery() + ")", "user")
  10. .setParameters(userQb.getParameters())
  11. .getRawMany();

或使用更优雅的语法:

  1. const posts = await connection
  2. .createQueryBuilder()
  3. .select("user.name", "name")
  4. .from(subQuery => {
  5. return subQuery
  6. .select("user.name", "name")
  7. .from(User, "user")
  8. .where("user.registered = :registered", { registered: true });
  9. }, "user")
  10. .getRawMany();

如果想添加一个子查询做为”second from”,请使用addFrom

你也可以在SELECT语句中使用子查询:

  1. const posts = await connection
  2. .createQueryBuilder()
  3. .select("post.id", "id")
  4. .addSelect(subQuery => {
  5. return subQuery
  6. .select("user.name", "name")
  7. .from(User, "user")
  8. .limit(1);
  9. }, "name")
  10. .from(Post, "post")
  11. .getRawMany();