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

deyfvvtc  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(602)

我想用laravel查询数据库中的排名,但不起作用
sql查询(它的作品)

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();
$top_students = 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");

这叫语法错误,怎么解决

lstz6jyr

lstz6jyr1#

试试这个:

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
");
oewdyzsn

oewdyzsn2#

原始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();
gz5pxeao

gz5pxeao3#

用这个

$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()

相关问题