typeorm querybuilder包括与查询无关的表吗?

时间:2019-10-12 17:55:43

标签: typescript typeorm

我目前正在尝试在typeorm中实现以下查询:

 select id,"createdAt", "updatedAt","deactivatedAt",(EXTRACT(EPOCH FROM "deactivatedAt" - "createdAt")/3600 ) as lifespan
    from (
       select id,"createdAt", "updatedAt","deactivatedAt", (EXTRACT(EPOCH FROM "deactivatedAt" - "createdAt")/3600 )as time
       from apartment_listing where active = false)as subquery
where subquery.time <24

为此,我在TypeScript中实现了以下代码:

    const mainQuery = this.repository
      .createQueryBuilder()
      .select("subquery.id", "id")
      .addSelect("subquery.time", "time")
      .addSelect("subquery.created", "createdAt")
      .addSelect("subquery.deactivated", "deactivatedAt")
      .from(qb => {
        const sub = qb.select(
          "(EXTRACT(EPOCH FROM listing.deactivatedAt - listing.createdAt )/3600 )",
          "time"
        )
        .addSelect("listing.deactivatedAt", "deactivated")
        .addSelect("listing.id", "id")
        .addSelect("listing.createdAt", "created")
        .addSelect("listing.active","active")
        .from(this.type, "listing")
        .where("listing.active = false")
        return sub;
      }, "subquery")
      .where("subquery.time < 24")

但是,执行此代码时,由typeorm生成的查询是不正确的,并导致无限查询,最终使用100%的内存。生成的查询是:

SELECT subquery.id AS "id", subquery.time AS "time", subquery.created AS "createdAt", subquery.deactivated AS "deactivatedAt" 
FROM "apartment_listing" "ApartmentListing", (SELECT "listing"."id" AS "id", "listing"."active" AS "active", "listing"."createdAt" AS "created", "listing"."deactivatedAt" AS "deactivated", (EXTRACT(EPOCH FROM "listing"."deactivatedAt" - "listing"."createdAt" )/3600 ) AS "time" FROM "apartment_listing" "listing" WHERE "listing"."active" = false) "subquery" 
WHERE subquery.time < 24

如您所见,在FROM子句中,它包含"apartment_listing" "ApartmentListing"表以及子查询。如果我将此查询复制并粘贴到PgAdmin中,它也会以无限查询结束,但是如果我从FROM子句中删除了多余的"apartment_listing" "ApartmentListing",表,则结果成功并且得到正确的结果。

为什么typeORM包含此"apartment_listing" "ApartmentListing",?在我的代码实现中,只有一个FROM,它指向子查询。如何摆脱多余的表,以便查询成功执行?

预先感谢

0 个答案:

没有答案