MySQL 计数子元素

MySQL count child elements

我有一个类别 table:

id | name |  parent_id
1  | Camaro | 0
2  | Chevelle | 0
3  | Sale - Camaro Parts | 1
4  | Bestselling Parts | 1

我的第一个请求是这样的:

'SELECT 
    * 
 FROM 
    `categories`
 WHERE
    parent_id = :parent_id';

在获取结果集后,我进行子查询以检查行是否包含子元素:

foreach($result as $r) {
    $r->hasChild    = count(ORM::forTable('categories')->where('parent_id', $r->id)->findArray());
    $data[]         = $r;
}

有什么方法可以避免在 foreach 循环中多次连接到数据库并在第一次查询中获取数据?

谢谢!

您可以对 parent_id 和 ID 上的 table 进行自连接。根据您是否想要带有子类别的类别,您可以进行左连接或内部连接。这里提到了类似的问题- Mysql Self Join to find a parent child relationship in the same table

这并不可怕,只要您只需要所选行下方 children 的计数即可。如果您想要整个层次结构,则需要使用更好的 RDMS。

此处解决方案的主要部分是自连接 table。然后我们可以使用count()聚合函数来查看每个项目附加了多少children。

select
  categories.id
  , categories.name
  , categories.parent_id
  , count(chld.id)
from
  categories
  left join categories chld
    on categories.id = chld.parent_id
where
  parent_id = :parent_id
group by
  categories.id
  , categories.name
  , categories.parent_id