我有一个数据库tbl_products
id parent_id product_name
1 0 abc
2 1 xyz
3 1 fgh
4 1 pqr
5 2 lmn
6 2 uvw
我想显示
等数据id child_count product_name
1 3 abc
2 2 xyz
3 0 fgh
4 0 pqr
5 0 lmn
6 0 uvw
答案 0 :(得分:2)
您可以使用以下查询:
SELECT id,
(SELECT COUNT(*)
FROM tbl_products
WHERE parent_id = t.id) AS child_count,
product_name
FROM tbl_products AS t
查询使用相关子查询来获取当前记录的子项数。
或者,您可以使用JOIN
:
SELECT t1.id,
COALESCE(t2.cnt,0) AS child_count,
t1.product_name
FROM tbl_products AS t1
LEFT JOIN (SELECT parent_id, COUNT(*) AS cnt
FROM tbl_products
GROUP BY parent_id
) AS t2 ON t1.id = t2.parent_id