這篇文章給大家分享的是有關laravel中子查詢&join的使用案例的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
讓客戶滿意是我們工作的目標,不斷超越客戶的期望值來自于我們對這個行業(yè)的熱愛。我們立志把好的技術通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領域值得信任、有價值的長期合作伙伴,公司提供的服務項目有:國際域名空間、網頁空間、營銷軟件、網站建設、唐山網站維護、網站推廣。本項目中關聯(lián)了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快照表庫的關聯(lián)數據,從而實現(xiàn)以下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'; })
實現(xiàn)上述需求完整代碼如下:
$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了一次,應該可以再優(yōu)化一下.
感謝各位的閱讀!關于“l(fā)aravel中子查詢&join的使用案例”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!