通过计数关联续订订单?

时间:2015-11-24 18:04:50

标签: mysql sequelize.js

我有UserPost表。 User has Many Posts关系。Post.belongsTo(User, {foreignKey: 'userId'}); User.hasMany(Post, {foreignKey: 'userId'}); User.findAll( { order: 'COUNT(Post) DESC', //??? include: [Post] }); 我想查询用户并按用户发布的帖子数量对查询进行排序。我该如何写这个续集查询?

StackPanel

如何按Post发布此用户查询?

4 个答案:

答案 0 :(得分:23)

可能有更好的方法,但您可以使用.literal()创建子查询并指定别名。然后,您可以在订购时引用别名,示例:

User.findAll({
    attributes: [
        'User.username',
        [sequelize.literal('(SELECT COUNT(*) FROM Posts WHERE Posts.userId = User.id)'), 'PostCount']
    ],
    order: [[sequelize.literal('PostCount'), 'DESC']]
});

这将生成以下SQL:

SELECT 
    `User`.`username`, 
    (SELECT COUNT(*) FROM Posts WHERE Posts.userId = User.id) AS `PostCount` 
FROM 
    `Users` AS `User` 
ORDER BY 
    PostCount DESC

答案 1 :(得分:0)

转过身让sequelize给你

SELECT  u.username,
        COUNT(*) AS PostCount
    FROM Users AS u
    JOIN Posts AS p  ON p.userId = u.userId
    GROUP BY u.userId, u.username
    ORDER BY PostCount DESC

也就是说,从Post开始,而不是用户。

答案 2 :(得分:0)

可能这可以工作

var User = objAllTables.User.User();
var Post = objAllTables.Post.Post();

User.hasMany(Post, {foreignKey: 'userId'});
Post.belongsTo(User, {foreignKey: 'userId'});


         User.hasMany(Post, {foreignKey: 'userId'});
            Post.belongsTo(User, {foreignKey: 'userId'});

            User.findAndCountAll({
                attributes: ['User.username'],
                include: [{ model: Post }]
            }).then(function (result) {
                 console.log(result.count);
                 console.log(result.rows);
            })

答案 3 :(得分:-1)

sequelize 有这个,但是你需要为计数创建一个别名

User.findAll({
  attributes: {
    include: [
       [sequelize.fn('COUNT', sequelize.col('Post.id')), 'count']
    ]
  },
  include: [{
    attributes: [],
    model:Post,
    duplicating: false,
    required: false
  }],
  group: ['User.id'],
  order: [['count', 'DESC']]
});