查询多表数据同时需要排序及分页

1、使用union

SELECT
    *
FROM
    (
        SELECT 1 AS type, `name`, number, money FROM test1
    UNION
        SELECT 2 AS type, `name`, number, money FROM test2
    ) a
ORDER BY
    number
LIMIT 0, 4

 

 

 在laravel中实现:

public function unionTest()
    {
        $sel = [
            '1 as type',
            'name',
            'number',
            'money',
        ];
        $test1 = Test::select(DB::raw(implode(',', $sel)));

        $sel = [
            '2 as type',
            'name',
            'number',
            'money',
        ];
        $result = Test2::select(DB::raw(implode(',', $sel)))
            ->union($test1);

        $sql = $result->toSql();
        $result = DB::table(DB::raw("($sql) as a "))
            ->mergeBindings($result->getQuery())
            ->limit(4)
            ->offset(4)
            ->orderBy('number', 'asc')
            ->get();
        dd($result);
    }

 备注:

union和union all的区别:

union all不会去重:

union会去重:

 

转载于:https://www.cnblogs.com/zhengchuzhou/p/10262260.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值