Hyperf2.1框架中使用子查询及用fromSub跟fromRaw实现子查询的区别测试
本来想到网上搜索一篇hyperf中实现子查询,没想到又得自己写,写一篇文章实实在在用Hyperf框架实现子查询;
功能需求:
在hyperf2.1框架中使用查询构造器编写一条带有子查询的sql语句。
实现环境:
hyperf2.1框架
实现的sql:(测试表是用上一篇文章的那个文章表,需要的自行在底部点击下一篇按钮查阅)
SELECT
cat_id , SUBSTRING_INDEX( GROUP_CONCAT( art_id ORDER BY pubtime DESC ), ',', 5 ) AS newids
FROM (
SELECT * FROM art ORDER BY pubtime DESC LIMIT 10000
) t
GROUP BY cat_id
ORDER BY pubtime DESC
测试方式:
在hyperf中启用sql数据记录功能
// 启用 SQL 数据记录功能
Db::enableQueryLog();
// 打印最后一条 SQL 相关数据
var_dump(Arr::last(Db::getQueryLog()));
实现方式方法:
fromSub
fromRaw
三种方式实现(其实是两种,其中一种分开写,个人比较喜欢这种)
实现方式1:
1.使用fromSub实现
$b = Db::table('art')
->select('cat_id',Db::raw('SUBSTRING_INDEX( GROUP_CONCAT( art_id ORDER BY pubtime DESC ), \',\', 5 ) AS newids'))
->fromSub('SELECT * FROM art ORDER BY pubtime DESC LIMIT 10000 ', 'a')
->groupBy('cat_id')->orderBy('pubtime','desc')
->get();
生成的sql:
array(3) {
["query"]=>
string(207) "select `cat_id`, SUBSTRING_INDEX( GROUP_CONCAT( art_id ORDER BY pubtime DESC ), ',', 5 ) AS newids from (SELECT * FROM art ORDER BY pubtime DESC LIMIT 10000 ) as `a` group by `cat_id` order by `pubtime` desc"
["bindings"]=>
array(0) {
}
["time"]=>
float(28.36)
}
实现方式2:
2.也是用fromSub
我这里加了两个where条件区分一下预编译的方式 如果比较复杂,或者需要分开写,在或者就是喜欢用链式的,个人比较喜欢这种
$a = Db::table('art')->select('*')->where('is_state',0)->where('is_del',1)->orderBy('pubtime','desc')->take(1000);
$b = Db::table('art')
->select('cat_id',Db::raw('SUBSTRING_INDEX( GROUP_CONCAT( art_id ORDER BY pubtime DESC ), \',\', 5 ) AS newids'))
->fromSub($a, 'a')
->groupBy('cat_id')->orderBy('pubtime','desc')
->get();
生成的sql:
array(3) {
["query"]=>
string(247) "select `cat_id`, SUBSTRING_INDEX( GROUP_CONCAT( art_id ORDER BY pubtime DESC ), ',', 5 ) AS newids from (select * from `art` where `is_state` = ? and `is_del` = ? order by `pubtime` desc limit 1000) as `a` group by `cat_id` order by `pubtime` desc"
["bindings"]=>
array(2) {
[0]=>
int(0)
[1]=>
int(1)
}
["time"]=>
float(41.32)
}
实现方式3:
3.fromRaw
$c = Db::table('art')
->select('cat_id',Db::raw('SUBSTRING_INDEX( GROUP_CONCAT( art_id ORDER BY pubtime DESC ), \',\', 5 ) AS newids'))
->fromRaw('( SELECT * FROM art ORDER BY pubtime DESC LIMIT 10000 ) t')
->groupBy('cat_id')->orderBy('pubtime','desc')
->get();
生成的sql:
array(3) {
["query"]=>
string(203) "select `cat_id`, SUBSTRING_INDEX( GROUP_CONCAT( art_id ORDER BY pubtime DESC ), ',', 5 ) AS newids from ( SELECT * FROM art ORDER BY pubtime DESC LIMIT 10000 ) t group by `cat_id` order by `pubtime` desc"
["bindings"]=>
array(0) {
}
["time"]=>
float(31.86)
}
如果你有其他的hyperf实现子查询的方式可以底部留言!
完
相关文章