如何使用原始查询Laravel查找排名

时间:2018-10-19 08:42:13

标签: mysql laravel syntax-error rank

我想使用laravel查询数据库中的排名,但不起作用

SQL查询(有效)

10, b 
20, a

20, a
10, b

我尝试使用

SELECT
    'id',
    'name',
    'local_pic',
    'point',
    FIND_IN_SET( 'point', ( SELECT GROUP_CONCAT( 'point' ORDER BY 'point' DESC )
        FROM 'students' )) AS rank
FROM 'students'
ORDER BY rank

-

$top_students = DB::table('students')
    ->select('id','name','local_pic','point',
    ->whereRaw("find_in_set('point',( SELECT GROUP_CONCAT( 'point' ORDER BY 'point' DESC ) FROM 'students' )) as rank"))
   ->orderBy('rank','DESC')
   ->get();

它调用语法错误,我该如何解决

3 个答案:

答案 0 :(得分:0)

使用此

$top_students = DB::table('students')
              ->select('id','name','local_pic','point')
              ->selectRaw("find_in_set('point',( SELECT GROUP_CONCAT( 'point' ORDER BY 'point' DESC ) FROM 'students' )) as rank")
              ->orderBy('rank','DESC')
              ->get();

您错过了一些后括号,现在语法错误已修复,接下来您可以通过将->get()更改为->toSql()

来检查查询

答案 1 :(得分:0)

您的原始SQL不包含where语句。另外,您正在使用whereRaw()添加原始选择查询,这是错误的。

尝试:

\DB::table('students')
    ->select(
        'id',
        'name',
        'local_pic',
        'point',
        \DB::raw("FIND_IN_SET( 'point', ( SELECT GROUP_CONCAT( 'point' ORDER BY 'point' DESC ) FROM 'students' )) AS rank")
    )
    ->orderBy('rank', 'DESC')
    ->get();

\DB::table('students')
    ->selectRaw("
        id,
        name,
        local_pic,
        point,
        FIND_IN_SET( 'point', ( SELECT GROUP_CONCAT( 'point' ORDER BY 'point' DESC ) FROM 'students' )) AS rank
    ")
    ->orderBy('rank', 'DESC')
    ->get();

答案 2 :(得分:0)

尝试一下:

DB::select("
    SELECT
        'id',
        'name',
        'local_pic',
        'point',
        FIND_IN_SET( 'point', ( SELECT GROUP_CONCAT( 'point' ORDER BY 'point' DESC )
            FROM 'students' )) AS rank
    FROM 'students'
    ORDER BY rank
");