【问题标题】:How to count only certain rows in a GROUP BY in Rails如何在 Rails 中仅计算 GROUP BY 中的某些行
【发布时间】:2021-01-15 14:41:46
【问题描述】:

在我正在构建的应用程序中,有帖子和标签,它们通过多对多关系连接。我想要做的是向用户显示所有标签,并根据他们有多少已发布的帖子对其进行排序(由帖子表中的 is_published 列确定)。

现在我正在使用此代码按照他们一般拥有的帖子数量(已发布和未发布)对它们进行排序:

scope :top_used, -> { left_joins(:posts).group(:id).order("COUNT(posts.id) DESC") }

翻译成 MySQL:

SELECT t.* 
  FROM tags t
  LEFT 
  JOIN post_tags pt
    ON pt.tag_id = tags.id 
  LEFT 
  JOIN posts p
    ON p.id = pt.post_id 
 GROUP 
    BY t.id  
 ORDER 
    BY COUNT(p.id) DESC

所以,我需要按已发布帖子的数量而不是所有帖子的数量来排序。这可以在 MySQL 中完成吗?

【问题讨论】:

    标签: mysql ruby-on-rails activerecord ruby-on-rails-6


    【解决方案1】:

    也许是这样的:

    SELECT `tags`.* FROM `tags` 
    LEFT OUTER JOIN `post_tags` ON `post_tags`.`tag_id` = `tags`.`id` 
    LEFT OUTER JOIN `posts` ON `posts`.`id` = `post_tags`.`post_id` AND posts.is_published = 1
    GROUP BY `tags`.`id` 
    ORDER BY COUNT(posts.id) DESC
    

    ?

    【讨论】:

      【解决方案2】:

      假设is_published列的数据类型为BooleanInteger,值10可以按值的总和排序:

      ORDER BY SUM(posts.is_published) DESC
      

      如果is_published 可以为空,请使用COALESCE()

      ORDER BY COALESCE(SUM(posts.is_published), 0) DESC
      

      【讨论】:

        猜你喜欢
        • 2012-01-22
        • 2015-10-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多