【问题标题】:How to use row value in where clause with sequelize API如何在带有 sequelize API 的 where 子句中使用行值
【发布时间】:2018-06-30 08:16:59
【问题描述】:

我想用sequelize来实现这个sql查询。

select id, date, comment
from posts
where (date, id) > ('2018-01-01', 1)
order by date, id
limit 10

这种查询用于无限滚动分页。关于如何做到这一点的任何想法?文档没有说明行值

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    正如@GondonLinoff 指出的那样,查询可以重写。 我已经使用 explain analyze 分析了 postgres 上两个查询的性能,它没有任何影响(似乎行值只是语法糖,但 dba 专家可以解释这一点)。

    所以,在接下来的 where 子句中应该被实现为:

    const filter = {}
    filter[Op.or] = [
      {
        date: {
          [Op.gt]: sinceDate
        }
      },
      {
        [Op.and]: {
          date: sinceDate,
          id: {
            [Op.gt]: sinceId
          }
      }
    }
    const result = await Posts.findAll({ where: filter })
    

    【讨论】:

      【解决方案2】:

      如果问题是where,可以改写为:

      where date > '2018-01-01' or (date = '2018-01-01' and id > 1)
      

      【讨论】:

      • @GorgonLinoff 我正在考虑这样做。但是你知道这对 Postgres 上的查询性能有什么影响吗?
      • @GuilhermeCaraciolo 。 . .您将需要尝试使用您的数据。我怀疑如果您在 (date, id) 上有索引,这可能会影响性能。
      猜你喜欢
      • 2014-11-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 2018-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多