简体   繁体   English

SQL:如何从复杂的联接中获取唯一值的出现次数?

[英]SQL: How to get an occurrence count of unique values from a query complicated by joins?

I have three tables: 我有三个表:

  • Content 内容
  • Content_Category 内容类别
  • Content_Class Content_Class

There are four types of Content Classes, and Content_Class has a Many:1 relationship with Content rows to link each content with 1 or more classes. 内容类有四种类型,并且Content_Class与内容行具有Many:1关系,以将每个内容链接到一个或多个类。

The same rule applies to categories, which also has a Many:1 relationship with content rows. 相同的规则适用于类别,类别与内容行也具有Many:1关系。

My goal is, given a set of content rows possibly filtered on category , what are the aggregate counts of the Content_Class rows per Class? 我的目标是,给定一组可能按类别过滤的内容行,每个类的Content_Class行的总计数是多少?

my current query: 我当前的查询:

SELECT cc.class_Id, COUNT(*) AS `records`
    FROM Content_Class cc
    LEFT JOIN Content c ON c.id = cc.content_id
    LEFT JOIN Content_Category ccat ON c.id = ccat.content_id
    WHERE cc.class_id IS NOT NULL
    GROUP BY cc.class_id';

This does not provide accurate counts, because for content that contain more than one category relation, the content row shows up once per category link in the query response, inflating the count of class occurrences. 这不会提供准确的计数,因为对于包含多个类别关系的内容,内容行在查询响应中的每个类别链接中显示一次,从而增加了类出现的次数。

For instance, if a content row is mapped to two categories, and two classes, it will show up four times, doubling the actual count of unique content-to-class relationships in the result... 例如,如果将内容行映射到两个类别和两个类别,它将显示四次,从而使结果中唯一的内容与类别关系的实际计数加倍...

What's the best query to get the UNIQUE count of all content class occurrences by UNIQUE content row? 通过UNIQUE内容行获取所有内容类出现的UNIQUE计数的最佳查询是什么?

You should try this: 您应该尝试这样:

    SELECT count(cc.class_id) FROM (SELECT distinct cc.class_Id, COUNT(*) AS `records`
    FROM Content_Class cc
    LEFT JOIN Content c ON c.id = cc.content_id
    LEFT JOIN Content_Category ccat ON c.id = ccat.content_id
    WHERE cc.class_id IS NOT NULL
    GROUP BY cc.class_id');

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

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