查詢多表數據同時須要排序及分頁

一、使用unionlaravel

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中實現:sql

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);
    }

 備註:spa

union和union all的區別:code

union all不會去重:blog

union會去重:get

相關文章
相關標籤/搜索