2014-09-10 61 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');