select sum(count) from (
--一级
select count(*) as count from table_name where pid= 'id'
union all
--二级
select count(*) as count from table_name t1
inner join table_name t2
on t1.pid = t2.id
where t2.pid= 'id'
union all
--三级
select count(*) as count from table_name t1
inner join (
select id,pid from table_name t1
inner join table_name t2
on t1.pid = t2.id
where t2.pid= 'id'
) t2 on t1.pid = t2.id
)