Search code examples
mysqlgroup-byinner-join

MySQL count records from 4 tables


I have 4 tables.

Table 1: articles (has some products)

Table 2: companies (has some companies ex. Mitsubishi, Haier etc)

Table 3: article_categories (has some categories ids connected with each product)

Table 4: article_company (has some companies ids connected with each product)

I have created the following sqlfiddle

http://sqlfiddle.com/#!9/2a3b8d7/15

I want to count the products for each company.

   SELECT comp.CompanyID,comp.title,comp.status,count(aco.ArticleID) as count_articles 
   FROM companies comp 
   inner join article_company aco on aco.CompanyID=comp.CompanyID 
   inner join articles art on art.ArticleID=aco.ArticleID 
   inner join article_category ac on ac.ArticleID=aco.ArticleID 
   where comp.status = 1
   AND ac.CategoryID IN (245,253,259,261,521,263,743) 
   group by comp.CompanyID;

When i run the query i get 18 instead of 15.

If i execute the following query i get 15 records.

    SELECT comp.CompanyID,comp.title,comp.status,count(aco.ArticleID) as count_articles 
    FROM companies comp 
    inner join article_company aco on aco.CompanyID=comp.CompanyID 
    inner join articles art on art.ArticleID=aco.ArticleID 
    where comp.status = 1
    group by comp.CompanyID;

Any suggestions to change the first query in order to get the results from the second query?


Solution

  • SELECT comp.CompanyID,
           comp.title,
           comp.status,
           count(DISTINCT aco.ArticleID) as count_distinct_articles
    FROM companies comp 
    inner join article_company aco on aco.CompanyID=comp.CompanyID 
    inner join articles art on art.ArticleID=aco.ArticleID 
    inner join article_category ac on ac.ArticleID=aco.ArticleID 
    where comp.status = 1
    AND ac.CategoryID IN (245,253,259,261,521,263,743) 
    group by comp.CompanyID;
    

    fiddle

    PS. Excess informational columns added - they are removed from the above query.