如何将 sql 查询转换为 TypeORM 查询生成器?
SELECT * FROM GameType
INNER JOIN
(SELECT Draw.GameTypeID AS GameID, MIN(Draw.DrawDate) AS DrawDate
FROM Draw
WHERE Draw.DrawDate >= GETDATE()
GROUP BY Draw.GameTypeID) AS New ON New.GameID=GameType.GameTypeID
您可以使用第二个查询生成器来生成连接子查询的 SQL:
const subquery = await getRepository(Draw)
.createQueryBuilder("Draw")
.select("Draw.GameTypeID", "GameID")
.addSelect("MIN(Draw.DrawDate)", "DrawDate")
.where("Draw.DrawDate >= :currentDate", { currentDate: new Date() })
.groupBy("Draw.GameTypeID");
const mainQuery = await getRepository(GameType)
.createQueryBuilder("GameType")
.innerJoin(
`(${subquery.getQuery()})`,
"New",
"New.GameID = GameType.GameTypeID"
)
.setParameters(subquery.getParameters())
.getMany();