【问题标题】:Sequelize with Postgresql order by with null values first使用 Postgresql 顺序排序,首先使用空值
【发布时间】:2019-10-18 02:30:02
【问题描述】:

我想构造一个 sequelize 查询,它首先以 NULL 值按升序返回行。

我在发送电子邮件时有一个时间戳,如果从未发送过电子邮件,则该时间戳为 NULL。

这是我想要的 Postgres 查询:

SELECT quote, quote_id
FROM quotes
WHERE book_id = '${book_id}'
ORDER BY last_emailed ASC NULLS FIRST
LIMIT 5

我的续集查询是:

const res = await Quote.findAll({
  attributes: ['quote', 'quote_id'],
  where: { book_id },
  order: [
    ['last_emailed', 'ASC']
  ],
  limit: 5,
})

但这会最后返回所有 NULL 值。否则它会做我想做的事

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    ASC 之后添加NULLS FIRST 应该会给您预期的结果:

    const res = await Quote.findAll({
       attributes: ['quote', 'quote_id'],
       where: { book_id },
       order: [
          ['last_emailed', 'ASC NULLS FIRST']
       ],
       limit: 5,
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多