【问题标题】:How to use subquery in sequelize to reference self table?如何在 sequelize 中使用子查询来引用 self 表?
【发布时间】:2021-10-15 14:57:04
【问题描述】:

我想使用 sequelize.queryGenerator 创建简单查询,并通过“文字”将其发送到模型查询以获取结果。基本思想是生成这样的查询:

select * from table t1
where id in ( 
  select id from table t2 
  where t1.productId = t2.productId 
  order by t2.validfrom desc limit 1
)

我总是可以对整个事情使用 rawQuery,但根据Sequelize - subquery in where clause 它应该能够在打字稿支持的情况下编写它。然而,当我将子查询引用到同一个表时,我的情况有所不同。我创建了以下代码:

const whereSubquery: FindOptions<Pricing> = {
    attributes: ['id'],
    where: {
        ProductId: 3,
        validFrom: new Date(2021, 9, 15),
    },
    order: [['validFrom', 'desc']],
    limit: 1,
};
const subQuery: string = this.queryGenerator
    .selectQuery(Pricing.name, whereSubquery)
    .slice(0, -1); // to remove the ';' from the end of the SQL

console.log(subQuery);

const result = await this.pricingRepository.findAll({
    where: {
        id: {
            [Op.in]: SequelizeTypeScript.literal(`(${subQuery})`),
        },
    },
});

console.log 按预期显示查询:

SELECT "id"
FROM "Pricing"
WHERE "Pricing"."ProductId" = 3
  AND "Pricing"."validFrom" = '2021-10-15 14:25:59.406 +00:00'
ORDER BY "validFrom"
DESC LIMIT 1

到目前为止一切顺利。我将用文字 t1."ProductId" 替换静态值“3”,但我需要表有“t2”作为别名。如果无法通过 FindOptions 中的任何参数实现,我可以想象使用正则表达式完成所有操作。疯狂但可以做到。

但是“this.pricingRepository.findAll”方法会产生以下错误:

SequelizeDatabaseError: relation "Pricing" does not exist

好吧,定价表确实与其自身没有关系,但在子查询中它不是预期的也不是必需的。

有什么简单的方法或者我应该直接去rawQuery然后用SQL手动写所有东西吗?

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:

    我终于用了两个独立的查询生成器和正则表达式将它们混合在一起。

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    相关资源
    最近更新 更多