【问题标题】:Specifying what records are returned from database depending on certain field with Sequelize and MySQL根据 Sequelize 和 MySQL 的特定字段指定从数据库返回的记录
【发布时间】:2022-01-26 15:41:05
【问题描述】:

我正在尝试获取数据库中的最新记录。我有一个包含他们类别的字段。我试图获得 20 条记录,每个类别中有 5 条最新帖子。我的意思是它应该返回 20 条最新记录,但每个类别返回 5 条,因为最新的 20 条并不一定意味着每个类别的平衡 5 条。基本上我在下面有什么,但我觉得有更好的方法并且无法从阅读 Sequelize 文档中看到它。谢谢大家,我真的很感激!请原谅伪代码。我有4个类别。实际上,我还按 createdAt 时间戳字段进行排序,其中包含限制和属性以及其他检查/错误处理,为了便于阅读,我没有包括在内。

Posts.findAll({ where: { category: "Tech"}})
.then(techPosts => {
     Posts.findAll({where:{category: "Science"},})
     .then(sciencePosts => {
          //actually 2 more nested findAlls before sending
          const posts = [...techPosts, ...sciencePosts]
          res.status(200).json(posts).end();
     })
})

【问题讨论】:

  • 最简单的解决方案是创建 4 个单独的查询,其中每个查询为一个明确的(硬编码)类别选择 5 个最新行,并将所有查询输出联合起来。如果类别列表是静态的并且将来不会扩展,请使用它。更复杂的解决方案(使用动态类别列表和/或每个类别数量的行)取决于精确的 MySQL 版本,并且可能使用子查询、CTE、窗口函数......并且它可能不太有效。
  • 附言。最简单的解决方案不能解决问题:当某个类别包含少于 5 行时,总输出将比需要的更小(将包含少于 20 行),并且不会通过从另一个类别添加更多行来扩展直到需要 20 行类别。
  • 谢谢@Akina,我会调查的,非常感谢

标签: javascript mysql node.js express sequelize.js


【解决方案1】:

我建议使用“Promise.all”同时获取 5 个不同的类别。 代码如下所示:

const fetchTechPosts = () => {
  return Posts.findAll({ where: { category: "Tech"}})
}

const fetchSciencePosts = () => {
  return Posts.findAll({ where: { category: "Science"}})
}

const promises = Promise.all([fetchTech, fetchScience])
promises.then(posts => {
  res.status(200).json(posts).end()
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    相关资源
    最近更新 更多