遇到的问题:
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();