查詢多表資料同時需要排序及分頁
阿新 • • 發佈:2019-01-13
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會去重: