简体   繁体   English

从MySQL中的两个联接表获取多个计数

[英]Getting multiple counts from two joined tables in MySQL

So I have two tables, categories and designs. 因此,我有两个表,类别和设计。 I want to construct a query that will fetch all categories, along with the count of any sub categories (categories.parent_id equal to the categories.id) AND the count of any designs (design.category_id equal to categories.id) 我想构造一个查询,该查询将获取所有类别以及所有子类别的计数(categories.parent_id等于category.id)和任何设计的计数(design.category_id等于category.id)

If I try to just get one of these counts, everything works fine, but when I try for both with the following code, the count for both is the same number (and not the correct number) for either. 如果我尝试仅获取这些计数之一,那么一切正常,但是当我使用以下代码尝试两者时,两者的计数都是相同的数字(而不是正确的数字)。

        $this->db->select('categories.id AS id, categories.parent_id AS parent_id, categories.title AS title, 
        categories.description AS description, categories.img_path AS img_path, COUNT(designs.id) AS design_count, 
        COUNT(sub_categories.id) as sub_category_count');
        $this->db->from('categories');
        $this->db->join('designs',                          'categories.id = designs.category_id', 'left');
        $this->db->join('categories as sub_categories',     'categories.id = sub_categories.parent_id', 'left');
        $this->db->group_by('categories.id');

Any help will be much appreciated, cheers! 任何帮助将不胜感激,加油!

Assuming that the root categories do not contain designs, here is the query that returns the necessary information: 假设根类别不包含设计,以下是返回必要信息的查询:

SELECT category.id, category.title, subcategory.id, designs.id
FROM categories category
LEFT JOIN categories subcategory ON category.id = subcategory.parent_id
LEFT JOIN designs ON subcategory.id = designs.category_id
WHERE category.parent_id IS NULL

Now all you need to do is to apply grouping: 现在,您需要做的就是应用分组:

SELECT category.id, category.title, COUNT(DISTINCT subcategory.id), COUNT(designs.id)
FROM categories category
LEFT JOIN categories subcategory ON category.id = subcategory.parent_id
LEFT JOIN designs ON subcategory.id = designs.category_id
WHERE category.parent_id IS NULL
GROUP BY category.id, category.title

The key here is the use of COUNT(DISTINCT ...) . 这里的关键是使用COUNT(DISTINCT ...)

SELECT c.id,c.title,
       IFNULL(sc.counted,0) AS subcategories,
       IFNULL(d.counted,0) AS designs
FROM categories c 
     LEFT JOIN 
     ( SELECT parent_id,COUNT(*) AS counted 
         FROM categories GROUP BY parent_id ) sc
       ON c.id=sc.parent_id
     LEFT JOIN
     ( SELECT category_id,COUNT(*) AS counted 
         FROM designs GROUP BY category_id ) d
       ON c.id=d.category_id
WHERE c.parent_id IS NULL ;

should get you the desired numbers as raw SQL. 应该为您提供所需的数字作为原始SQL。

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

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