【发布时间】:2020-03-19 07:29:24
【问题描述】:
我对@987654322@ 和having 加上count 进行了以下查询。它应该只返回那些具有在group by 子句中指定的列以及由having count x 指定的计数的行。
我认为下面的查询应该是正确的:
@articles = Article.joins(:taggings)
.where(taggings: { tag_id: @article_tags_ids, taggable_type: "Article"})
.group('articles.id')
.having("count(taggings.tag_id) = ?", @article_tags_count)
在这种情况下,它应该只返回那些具有用户搜索的那些标签的文章,仅此而已。
架构来自本教程: https://cobwwweb.com/rails-has-many-through-polymorphic-association
它创建这个 SQL
SELECT
`articles`.*
FROM
`articles`
INNER JOIN `taggings`
ON `taggings`.`taggable_id` = `articles`.`id`
AND `taggings`.`taggable_type` = 'Article'
WHERE
`taggings`.`tag_id` IN (1, 3)
AND `taggings`.`taggable_type` = 'Article'
GROUP BY
articles.id
HAVING
(count(taggings.tag_id) = 2)
LIMIT 11
【问题讨论】:
标签: sql ruby-on-rails join tags