【问题标题】:Dual counts on query results in SequelizeSequelize 中查询结果的双重计数
【发布时间】:2020-06-03 23:15:05
【问题描述】:

我正在处理一个返回用户名、ID 以及属于该用户的操作和 cmets 的数量的查询。这是 SQL 中的查询:

SELECT users.id, users.name, (
    SELECT count(*) from actions where users.id = actions.user_id
  ) as Action_Count, (
    SELECT count(*) from comments where users.id = comments.user_id
  ) as Comment_Count
FROM users

我对 Sequelize 有点陌生,但是经过太多小时的搜索和无数次尝试,我似乎无法弄清楚如何正确编写它。所以我希望这里有人可以帮助指导我。这是我最好的尝试:

 User.findAll({
  attributes: ['name','id',
    [Sequelize.fn('count', Sequelize.col('actions.user_id')), 'count_of_actions'],
    [Sequelize.fn('count', Sequelize.col('comments.user_id')), 'count_of_comments']
  ],
  include: [{ attributes: [], model: Action },{ attributes: [], model: Comment }],
  group: ['user.id'],
  order: [['createdAt', 'ASC']]
})

但是如果有任何 cmets,这对于 Action_CountComment_Count(两者相乘)返回相同的数字。

非常感谢任何帮助或指导!

【问题讨论】:

  • 我使用sequelize.query 运行上面的sql查询,它有效。如果可能的话,我仍然很好奇如何使用 sequelize 语法来做到这一点。

标签: sequelize.js


【解决方案1】:

我今天也面临同样的问题。这是我通过添加不同的功能来解决问题的方法:

 User.findAll({
  attributes: ['name','id',
    [Sequelize.fn('count', Sequelize.fn('DISTINCT', Sequelize.col('actions.user_id'))), 'count_of_actions'],
    [Sequelize.fn('count', Sequelize.fn('DISTINCT', Sequelize.col('comments.user_id'))), 'count_of_comments']
  ],
  include: [{ attributes: [], model: Action },{ attributes: [], model: Comment }],
  group: ['user.id'],
  order: [['createdAt', 'ASC']]
})

帖子太旧了,希望对大家有所帮助。

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2022-08-19
    • 2013-09-26
    • 2016-07-11
    • 2015-11-30
    • 2019-05-17
    • 2015-08-21
    • 1970-01-01
    • 2015-11-08
    相关资源
    最近更新 更多