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


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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM