所以我有两张桌子,类别和设计。我想构建一个查询,它将获取所有类别,以及任何子类别的计数(categories.parent_id等于categories.id)和任何设计的计数(design.category_id等于categories.id)
如果我试图获得其中一个计数,一切正常,但是当我尝试使用以下代码时,两者的计数都是相同的数字(而不是正确的数字)。
$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');
欢迎任何帮助,欢呼!
答案 0 :(得分:3)
假设根类别不包含设计,这里是返回必要信息的查询:
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
现在您需要做的就是应用分组:
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
这里的关键是使用COUNT(DISTINCT ...)
。
答案 1 :(得分:0)
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 ;
应该为您提供所需的数字作为原始SQL。