Sql查询显示组的计数(*),同时保留组的所有行

时间:2014-09-10 17:47:31

标签: php sql laravel-4 group-by eloquent

我有一张类似以下的表

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查询(喜欢Gluent或Eloquent for 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

对它们进行排序

我怎样才能实现它?

2 个答案:

答案 0 :(得分:1)

我不知道Fluent,Eloquent和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

答案 1 :(得分:0)

我根据segio0983

的答案通过以下Fluent查询解决了这个问题
 $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');