2014-09-10 71 views
-1

我有以下SQL查询,以显示组COUNT(*),同时保持该组中的所有行

id user_id  father_id 
1 1    1 
2 2    1 
3 3    2 
4 4    2 
5 5    2 
6 6    3 
7 7    4 

我搜索一个SQL查询类似的表(喜欢流利伶牙俐齿的Laravel 4)给我以下结果:

id user_id  father_id family_members 
3 3    2    3 
4 4    2    3 
5 5    2    3 
1 1    1    2 
2 2    1    2 
6 6    3    1 
7 7    4    1 

因为它可以观察family_members是谁具有相同father_id

select id, user_id, father_id, count(*) as family_members from users group by father_id 
用户数

上面的查询,只是保持每个组的第一行,但我想保留所有其他记录,而不仅仅是第一个;然后根据family_members,然后根据father_id

排序他们如何才能实现它?

回答

1

我不知道流利,也没有雄辩,也没有Laravel 4,但sql查询会是这样的。

SELECT yourTable.*, auxTable.family_members 
    FROM yourTable 
    LEFT JOIN 
    (
     SELECT father_id, COUNT(id) as family_members 
     FROM yourTable 
     GROUP BY father_id 
    )auxTable ON yourTable.father_id = auxTable.father_id 
ORDER BY family_members DESC, yourTable.father_id ASC 
0

我通过基于回答以下流利查询解决了这个问题,从segio0983

$users = DB::table('users') 
    ->leftjoin(DB::raw('(SELECT father_id, COUNT(id) as family_members 
     FROM users 
     GROUP BY father_id) auxTable '),function($join) 
     { 
      $join->on('users.father_id', '=', 'auxTable.father_id'); 
     }) 
    ->orderBy('auxTable.family_members','desc') 
    ->orderBy('users.father_id','asc') 
    ->select('users.id','users.father_id','auxTable.family_members');