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

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会去重:

 

posted @ 2019-01-13 12:19  郑楚周  阅读(2195)  评论(0编辑  收藏  举报