简体   繁体   English

为什么我的查询没有提供单一的结果?

[英]Why doesn’t my query deliver singular results?

I have following query with group by and having plus count .我有以下与查询group by ,并havingcount It should return only those rows having columns specified in the group by clause with the count specified by having count x .它应该只返回那些在group by子句中指定了列having count xhaving count x指定的行。

I think the following query should be correct:我认为以下查询应该是正确的:

@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)

In this case, it should only return those articles, that have those and exactly those tags the user searched for and none more.在这种情况下,它应该只返回那些具有用户搜索的那些标签的文章,仅此而已。

Schema is from this tutorial: https://cobwwweb.com/rails-has-many-through-polymorphic-association架构来自本教程: https : //cobwwweb.com/rails-has-many-through-polymorphic-association

It creates this SQL它创建了这个 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

The solution is following SQL Query with not one but two joins on the join-table.解决方案是在连接表上使用不是一个而是两个连接的SQL 查询 I don't know what substantial difference that makes, but obviously for the database it does make one, even if it can match articles with tags with a single join already.我不知道这有什么实质性的不同,但显然对于数据库来说,它确实可以产生一个,即使它已经可以通过单个join匹配带有标签的文章。

SELECT  
`articles`.*
FROM `articles`
JOIN `taggings` 
ON `articles`.`id` = `taggings`.`taggable_id` 
JOIN `tags` ON `taggings`.`taggable_id` = `tags`.id 
WHERE `tags`.`id` in (1,2,3) 
GROUP BY `articles`.id 
HAVING( COUNT(`tags`.`id`) = 3);

Such that when you have two articles, article-one and article-two, where article-one matches tag1, tag2, tag3 and article-two also matches tag1, tag2, tag3 and over that tag4, the query only returns article-one.这样,当您有两篇文章时,文章一和文章二,其中文章一匹配 tag1、tag2、tag3 并且文章二也匹配 tag1、tag2、tag3 和 tag4,查询只返回文章一。 The conjunction is a "this" and "nothing more" and not an or连词是“这个” and “仅此而已”而不是一个or

Yours你的

vonSpotz冯斯波茨

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM