富贵资源网 Design By www.hznty.com
本项目中关联了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语句会只有'"htmlcode">$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的使用就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com
暂无评论...
稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!
昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。
这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。
而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?