2016-08-08 5 views
-3

나는 chidren 수를 얻고 싶습니다. 나는이 쿼리를 시도하지만 테이블 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 절을 사용해보십시오. PARENT_ID, father_id 이름으로

선택 ID는, 당신은 두 번 테이블 users을 사용하는 PARENT_ID

2

하여 사용자 그룹에서 아이 으로 (사용자 father_id = PARENT_ID를 SELECT * FROM) 계산합니다. 당신의 말을 두 어떤 기록을 보여주기 위해 테이블 ​​별칭을 사용

select 
    id as parent_id, 
    father_id, 
    name, 
    (select count(*) from users c where c.father_id = p.id) as children 
from users p; 
관련 문제