TP5 使用 union 后 order by 排序与 paginate分页
2020-02-12 16:41
609 查看
**TP5 使用 union 后 order by 排序与 paginate分页**
在项目开发过程中遇到需要使用 union() 方法的情况,出现了很多问题,于是记录一下。
在最开始时使用
[code]$listInfo = (new AdminFinancial())->alias('f') ->field('f.*,fa.adjustment_type as details_type,fa.currency_amount,fa.currency_code') ->join('admin_financial_adjustment fa ',"f.id = fa.financial_id" ,"left") ->where("fa.currency_amount != 0") ->union("SELECT f.*,fc.charge_type as details_type,fc.currency_amount,fc.currency_code FROM `admin_financial` `f` inner JOIN `admin_financial_charge` `fc` ON `f`.`id` = fc.financial_id WHERE f.auth_id = '$shop_id' AND f.poste_date BETWEEN '$start_date' AND '$end_date' and fc.currency_amount != 0") ->union("SELECT f.*,ff.fee_type as details_type,ff.currency_amount,ff.currency_code FROM `admin_financial` `f` inner JOIN `admin_financial_fee` `ff` ON `f`.`id` = ff.financial_id WHERE f.auth_id = '$shop_id' AND f.poste_date BETWEEN '$start_date' AND '$end_date' and ff.currency_amount != 0 ") ->select();
后,可以查出所需数据,但加入 order() 进行排序时,会出现
Incorrect usage of UNION and ORDER BY
这种错误,把order by 放入到 union 子句中也并没有什么效果,之后经过查找资料发现可以构建子查询进行解决
[code]$info1 = (new AdminFinancial())->alias('f') ->field('f.*,fa.adjustment_type as details_type,fa.currency_amount,fa.currency_code') ->join('admin_financial_adjustment fa ',"f.id = fa.financial_id" ,"left") ->where("fa.currency_amount != 0") ->buildSql(); $info2 = (new AdminFinancial())->alias('f') ->field('f.*,fc.charge_type as details_type,fc.currency_amount,fc.currency_code') ->join('admin_financial_charge fc ',"f.id = fc.financial_id" ,"left") ->where("fc.currency_amount != 0") ->buildSql(); $info3 = (new AdminFinancial())->alias('f') ->field('f.*,ff.fee_type as details_type,ff.currency_amount,ff.currency_code') ->join('admin_financial_fee ff ',"f.id = ff.financial_id" ,"left") ->where("ff.currency_amount != 0") ->union([$info1,$info2]) ->buildSql(); $listInfo = db::table($info3.' as f') ->order("f.id asc") ->paginate('10', false, ['page' => '1']) ->toArray();
结果正确,分页也可以使用。
注意:构建子查询是 查询字段需要保持一致
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- TP5分页使用方法,在使用paginate(10)后无法foreach得到的数据集合
- 解决SQL Server查询中使用Union或Union All后Order by排序无效的bug(好神奇啊!!)
- 分组 分页查询 (group by 和order by使用 )
- hive:数据库“行专列”操作---使用collect_set/collect_list/collect_all & row_number()over(partition by 分组字段 [order by 排序字段])
- UNION中ORDER By的使用
- order by排序使用联合索引
- Oracle中使用Order By排序时结果顺序不稳定的解决办法
- 使用bootstraptable插件实现表格记录的查询、分页、排序操作
- Order by 和 group by 的联合使用 并对某一字段中的不同结果进行重命名和自由排序
- TP5 paginate()分页后给结果集追加字段和数据
- 在ASP.NET MVC中使用Boostrap实现产品的展示、查询、排序、分页
- 使用MVC,实现多条件查询,排序与分页 的 存储过程
- 使用SELECT赋值时再用ORDER BY排序所产生的问题
- SQL 语句中union all和order by同时使用
- MyBatis排序时使用order by 动态参数时需要注意,用$而不是#
- order by居然不能直接在union子句中使用
- oracle使用order by排序null值如何处理
- 解决oracle使用rownum排序分页排序字段不唯一导致分页错误
- mybatis分页插件的使用(电商项目前端动态查询排序)
- flask数据分页paginate的使用(flask学习)