selectRaw中的Raw Sub Query

时间:2018-01-27 06:49:26

标签: mysql laravel-5.4

 BowlerMaster::selectRaw(" 
    tour_id, bowler_id, bowler_name, ball_team,
    SUM(balls) AS balls,
    SUM(overs) AS overs,                
    DB::raw('SELECT runs, wicket FROM bowler_master WHERE tour_id = ".$request->tour_id." AND bowler_id = ".$request->player_id." ORDER BY wicket DESC, runs LIMIT 1 AS bbi')
        ")
->where($where_array)
->groupby(['tour_id','bowler_id'])
->get()->first();

在上面的Eloquent Query中我想使用原始查询或任何其他方法来获取原始查询的结果以获取bbi的值,但是我收到以下错误:

  

SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;查看与您的MariaDB服务器版本对应的手册,以便在':: raw('SELECT match_id,run,wicket FROM bowler_master WHERE tour_id = 1 AND bo'在第25行附近使用正确的语法。

我正在编写此查询以生成以下输出

{
    "status": 200,
    "message": "Success",
    "bowler": {
        "tour_id": 1,
        "bowler_id": 21,
        "bowler_name": "Kaushal Chauhan",
        "ball_team": null,
        "balls": "29",
        "overs": 4.5,
        "bbi": 9/3,
    }
}

升级过度计算,一切正常。我没有得到如何获得“bbi”键:价值 注意:查询结果将在响应数组中推送,并将转换为json以获得上面显示的输出。

请指导。

1 个答案:

答案 0 :(得分:1)

试试这个

BowlerMaster::selectRaw("tour_id, bowler_id, bowler_name, ball_team, SUM(balls) AS balls,SUM(overs) AS overs")
        ->selectSub("  
                   SELECT runs 
                   FROM bowler_master 
                   WHERE tour_id = ".$request->tour_id." 
                   AND bowler_id = ".$request->player_id." 
                   ORDER BY wicket DESC, runs LIMIT 1
        ","runs")
        ->selectSub("  
                    SELECT wicket 
                    FROM bowler_master 
                    WHERE tour_id = ".$request->tour_id." 
                    AND bowler_id = ".$request->player_id." 
                    ORDER BY wicket DESC, runs LIMIT 1
           ","wicket")
        ->where($where_array)
        ->groupby(['tour_id','bowler_id'])
        ->get()->first();

在laravel中编写select子查询的规则如下:

DB::table('tablename')
    ->select('column name','..')
    ->selectSub("Your full query","alias name")
    ->get()