问题描述
在我正在构建的应用程序中,有帖子和标签,它们通过多对多关系连接。我想要做的是向用户显示所有标签,并按照他们发布的帖子数量(由帖子表中的 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 中完成吗?
解决方法
也许是这样:
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
?
,假设列 is_published
的数据类型是 Boolean
或 Integer
,值 1
或 0
您可以按总和排序值:
ORDER BY SUM(posts.is_published) DESC
如果 is_published
可为空,则使用 COALESCE()
:
ORDER BY COALESCE(SUM(posts.is_published),0) DESC