我想要计算孩子数。我尝试此查询,但无法工作 表colums如何计算用户的子女数
ID, father_id, 名
select id As parent_id , father_id ,name, count(select * from users WHERE father_id = parent_id) As child
from users
我想要计算孩子数。我尝试此查询,但无法工作 表colums如何计算用户的子女数
ID, father_id, 名
select id As parent_id , father_id ,name, count(select * from users WHERE father_id = parent_id) As child
from users
使用相关子查询数:
select id As parent_id , father_id ,name, (select count(*) from users u2
WHERE u2.father_id = u1.id) As child
from users u1
你试过这个,而不是使用*,得到您想要计算的特定字段:
select id As parent_id , father_id ,name, count(select name from users WHERE father_id = parent_id) As child
from users
请尝试使用group_by子句。
选择ID作为PARENT_ID,father_id,名称,由PARENT_ID
数(SELECT * FROM用户WHERE father_id = PARENT_ID)作为孩子 从用户群正在使用的表users
两次。使用表别名,以显示你说什么呢记录两种的:
select
id as parent_id,
father_id,
name,
(select count(*) from users c where c.father_id = p.id) as children
from users p;
能否请您指定与数据表,所以我们有清晰的思路 –
什么错误说? –