简体   繁体   中英

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

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.

The same rule applies to categories, which also has a Many:1 relationship with content rows.

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?

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?

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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