首页 > 解决方案 > Typeorm 子查询

问题描述

此 MS SQL 查询通过查询不包括周末和节假日的日历表,返回距给定开始日期(21 年 3 月 1 日)189 个工作日后的结束日期。这是基本的 SQL 查询:

select Top 1 TheDate as EndDate
FROM (select Top 189 d.TheDate from DateDimension d
LEFT JOIN USHolidayDimension h
ON d.TheDate = h.TheDate
where d.TheDate>='03/01/2021'
and IsWeekend=0 and H.TheDate is null
order by d.TheDate) as BusinessDays
order by TheDate DESC

此查询正确返回 21 年 11 月 24 日的日期,即从 21 年 3 月 1 日起的 189 个工作日。

我尝试了几种在 QueryBuilder 中编写它的方法,但不断收到错误无法构建查询,因为未设置主别名(调用 qb#from 方法)”

这是我的第一个查询:

const endDate = await getConnection()
.createQueryBuilder()
.select("select Top 1 TheDate as EndDate " +
"FROM (select Top 189 d.TheDate from DateDimension d" +
"LEFT JOIN USHolidayDimension h " +
"ON d.TheDate = h.TheDate " +
"where d.TheDate>='03/01/2021'" +
"and IsWeekend=0 and H.TheDate is null "+
"order by d.TheDate) as BusinessDays " +
"order by TheDate DESC")
.getRawMany();

这是我的第二次尝试-相同的错误消息:

const endDate = await connection .createQueryBuilder() .select("Top 1 TheDate", "Top1")
.addSelect(subQuery => {
return subQuery
.select("Top 189 d.TheDate")
.from("DateDimension", "d")
.leftJoinAndSelect("USHolidayDimension", "h", "d.TheDate = h.TheDate")
.where( "d.TheDate>='03/01/2021'")
.andWhere("IsWeekend=0 and H.TheDate is null")
}, "businessDays")
.getMany();

可能只是一个愚蠢的错误,但我似乎无法弄清楚。

标签: subquerytypeorm

解决方案


要像在第一个示例中那样使用原始 SQL 进行查询,您需要按照 TypeOrm 文档中的EntityManager APIEntityManager.Query中的描述使用。

什么是 EntityManagerEntityManager中描述了如何获取。

例子:

    const connection = await createConnection();
    const entitymanager = connection.manager;
    let result = await entitymanager.query("select top 1 TheDate from DateDimension order by TheDate desc");
    let theDate = result[0].TheDate;

推荐阅读