您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關laravel中子查詢&join的使用案例的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
本項目中關聯了2個數據庫
'default' => env('DB_CONNECTION', 'mysql'), //默認使用mysql為連接庫 'connections' => [ 'mysql' => [ 'driver' => 'mysql', 'host' => '192.168.0.xx', 'database' => 'database', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => 'tb_', 'strict' => false, ], 'mysql_snapshot' => [ 'driver' => 'mysql', 'host' => env('DB_HOST_SNAPSHOT', '192.168.0.xx'), 'database' => env('DB_DATABASE_SNAPSHOT', 'snapshot'), 'username' => env('DB_USERNAME_SNAPSHOT', 'root'), 'password' => env('DB_PASSWORD_SNAPSHOT', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => 'tb_', 'strict' => false, ], ],
在某個需求中,需要使用子查詢獲取snapshot快照表庫的關聯數據,從而實現以下sql邏輯
SELECT ... From (SELECT sum(game_count) AS sum_count, max(game_count) AS max_count, game_room_id, record_date FROM `tb_xx_snapshot` WHERE record_date BETWEEN '2017-05-17' AND '2017-05-23' AND type = '1' GROUP BY game_room_id) as main INNER JOIN `tb_xx_snapshot` AS `tb_gg` ON tb_gg.game_count = main.max_count and tb_gg.game_room_id = main.game_room_id where tb_gg.record_date BETWEEN '2017-05-17' AND '2017-05-23' AND tb_gg.type = '1' GROUP BY tb_gg.game_room_id;
其中子查詢主要用到以下query builder語句
$query = DB::table('xx_snapshot')->where('xx','yy')->groupBy('xx'); $main = DB::connection('mysql_snapshot') ->table(DB::raw("({$query->toSql()}) as tb_main")) ->mergeBindings($query->getQuery()) // 綁定參數,否則sql語句會只有'?' ->get();
而join語句中可傳入匿名函數重新構造,如再其中加多幾個連接條件,或者查詢條件
$con = DB::table('xx_snapshot') ->join('xx_snapshot as gg', function ($query) { $query->on('gg.game_count', '=', 'xx_snapshot.max_count') ->on('gg.game_room_id', '=', 'xx_snapshot.game_room_id') ->where('gg.xx','123'; })
實現上述需求完整代碼如下:
$subQuery= GameroomModel::select(DB::raw('sum(game_count) as sum_count,max(game_count) as max_count,record_date,game_room_id')) ->whereBetween('record_date',[$beginDay,$endDay]) ->where('type','1') ->groupBy('game_room_id'); $main = DB::connection('mysql_snapshot') ->table(DB::raw("({$subQuery->toSql()}) as tb_main")) ->mergeBindings($playerGame->getQuery()) ->join('gameroom_snapshot as gg', function ($join) { $join->on('gg.game_count', '=', 'main.max_count') ->on('gg.game_room_id', '=', 'main.game_room_id'); }) - >select('main.max_count','main.sum_count','gg.record_date','main.game_room_id') ->whereBetween('gg.record_date',[$beginDay,$endDay]) ->groupBy('main.game_room_id') ->get();
代碼中子查詢和外層都group by了一次,應該可以再優化一下.
感謝各位的閱讀!關于“laravel中子查詢&join的使用案例”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。