我想得到孩子的数量。我尝试这个查询,但没有工作 table 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
答案 0 :(得分:3)
使用相关的子查询来计算:
select id As parent_id , father_id ,name, (select count(*) from users u2
WHERE u2.father_id = u1.id) As child
from users u1
答案 1 :(得分:2)
您正在使用表格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;
答案 2 :(得分:0)
尝试使用group_by子句。
select id as parent_id,father_id,name,count(select * from users WHERE father_id = parent_id)as child 来自parent_id的用户组
答案 3 :(得分:-1)
您是否尝试过此操作,而不是使用*,获取您想要计算的特定字段:
select id As parent_id , father_id ,name, count(select name from users WHERE father_id = parent_id) As child
from users