Welcome Guest, Not a member yet? Register   Sign In
How to select multiple counts from multiple tables
#9

[eluser]markup2go[/eluser]
I figured it out, I think. Please correct me if I'm doing something wrong.

Code:
$this->db->select('product_sections.*, COUNT(DISTINCT(c.id)) as totalCats, COUNT(DISTINCT(s.id)) as totalSubcats, COUNT(DISTINCT(p.id)) as totalProducts', FALSE);
$this->db->join('product_categories as c', 'product_sections.id = c.section_id', 'left');    
$this->db->join('product_subcategories as s', 's.category_id = c.id', 'left');    
$this->db->join('products as p', 'p.subcategory_id = s.id', 'left');        
$this->db->group_by('product_sections.id');
$this->db->order_by('product_sections.name', 'asc');

And it produces this query:
SELECT product_sections.*, COUNT(DISTINCT(c.id)) as totalCats, COUNT(DISTINCT(s.id)) as totalSubcats, COUNT(DISTINCT(p.id)) as totalProducts
FROM (product_sections)
LEFT JOIN product_categories as c ON product_sections.id = c.section_id
LEFT JOIN product_subcategories as s ON s.category_id = c.id
LEFT JOIN products as p ON p.subcategory_id = s.id
GROUP BY product_sections.id
ORDER BY product_sections.name asc


Messages In This Thread
How to select multiple counts from multiple tables - by El Forum - 09-02-2009, 03:09 PM
How to select multiple counts from multiple tables - by El Forum - 09-02-2009, 06:13 PM
How to select multiple counts from multiple tables - by El Forum - 09-02-2009, 08:28 PM
How to select multiple counts from multiple tables - by El Forum - 09-03-2009, 05:44 AM
How to select multiple counts from multiple tables - by El Forum - 09-03-2009, 05:58 AM
How to select multiple counts from multiple tables - by El Forum - 09-03-2009, 06:16 AM
How to select multiple counts from multiple tables - by El Forum - 09-03-2009, 06:21 AM
How to select multiple counts from multiple tables - by El Forum - 09-03-2009, 06:27 AM
How to select multiple counts from multiple tables - by El Forum - 09-03-2009, 07:56 AM



Theme © iAndrew 2016 - Forum software by © MyBB