subquery - 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();
可能只是一个愚蠢的错误,但我似乎无法弄清楚。
解决方案
要像在第一个示例中那样使用原始 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;
推荐阅读
- facebook-graph-api - 来自 Facebook 访问令牌的 OAuth 异常错误
- php - 有没有办法避免第一个和第二个选项卡上的重复数据?PHP 代码点火器
- node.js - Plesk 上的节点应用程序 - 自定义脚本上的环境变量
- java - 如何从 YouTube 上的频道中检索订阅者列表?
- java - 调用 createSheet 和 trackAllColumnsForAutoSizing poi 时出错
- node.js - 使用创建反应应用程序反应应用程序服务器不会自动重启
- kubernetes-ingress - 如何使用 nginx 入口根据端口路由流量
- javascript - 需要根据对象数组中的连续对象属性或属性获取元素,我有一个要搜索的值
- javascript - 如何根据行中高度最大的卡片的高度设置卡片高度
- assembly - 为什么引导加载程序只能接受 16 位汇编