关于thinkphp union多表关联查询 后排序及分页实现

遇到的问题:

1、union后直接排序或分页报错  

        Incorrect usage of UNION and ORDER BY?
2、fetchSql得到的查询语句是没有"()"括起来的,
3、buildSql 得到的查询语句有 "()"括起来的;

例如:

查询语句一:(因为我关联的表有点多,自己适当修改)

$matField = "*"   // 查询的字段

$matSql = Db::name('product')
    ->alias(['product' => 'p', 'match_goods' => 'b', 'match_goods_son' => 'c', 'area' => 'd'])
    ->field($matField)
    ->join('match_goods', 'b.product_id = p.product_id')
    ->join('match_goods_son', 'c.match_goods_id = b.match_goods_id')
    ->join('area', 'p.province = d.id')
    ->where($where)
    ->where(['p.type' => 3, 'p.status' => 2])
    ->buildSql();
查询语句二:
$actField = '*' //字段
$data = Db::field($actField)
    ->name('product')
    ->alias(['product' => 'p', 'activity_goods' => 'b', 'activity_goods_son' => 'c', 'area' => 'd'])
    ->join('activity_goods', 'b.product_id = p.product_id')
    ->join('activity_goods_son', 'c.activity_goods_id = b.activity_goods_id')
    ->join('area', 'p.province = d.id')
    ->where($where)
    ->where(['p.type' => 2, 'p.status' => 2])
    ->union($matSql, true)
    ->select(false);

注意:$matField 和$actField 字段名称要一致,且顺序也要一致

$sql = "($data)";
 $res = Db::table($sql.' as a')->field('xx') // 这里xx与$matField 和$actField 字段名称要一致
          ->order('a.sort DESC, a.sign_start_time DESC')
          ->group('a.product_id')
          ->page(1, 10)
          ->select()->toArray();







  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值