2016-08-08 25 views
-3

我想要計算孩子數。我嘗試此查詢,但無法工作 表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 
+1

能否請您指定與數據表,所以我們有清晰的思路 –

+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

你試過這個,而不是使用*,得到您想要計算的特定字段:

select id As parent_id , father_id ,name, count(select name from users WHERE father_id = parent_id) As child 
    from users 
0

請嘗試使用group_by子句。

選擇ID作爲PARENT_ID,father_id,名稱,由PARENT_ID

2

數(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;