前言:
而今咱们对“thinkphpmysql”可能比较珍视,我们都需要剖析一些“thinkphpmysql”的相关文章。那么小编也在网上搜集了一些关于“thinkphpmysql””的相关文章,希望小伙伴们能喜欢,大家快快来了解一下吧!今天用tp6实现了一对多表,分别统计各个表中的某个字段的sum,然后group 主表中后,想着把这个方法分享给大家,并且以后用到了tp6实现复杂的mysql也放到这篇文章中,方便自己查看使用。
1、一张主表:用户表user:id,name(姓名),money(账户金额);两张分表:订单表 order:id,uid(用户ID),money(金额);资金表fund:id,uid,money(金额);将用户的姓名、账户金额、订单总金额,资金变动总金额一起查询出来:
原生mysql:
select u.*,o.order_money,f.fund_money from user uleft join(select uid,sum(money) as order_money from order group by uid) o on o.uid = u.idleft join(select uid,sum(money) as fund_money from fund group by uid) f on f.uid = u.id
tp6实现:
$list=Db::name("user")->alias("u")->where($where)->field("u.*,o.order_money,f.fund_money") ->join("(select uid,sum(money) as order_money from order group by uid) o",'o.uid = u.id','left') ->join("(select uid,sum(money) as fund_money from fund group by uid) f",'f.uid = u.id','left') ->page(PAGE,LIMIT)->order("u.id desc")->select()->toArray();
标签: #thinkphpmysql