需求: 分組聯合查詢,或者最新記錄。
問題: mysql分組的時候默認會查詢第一條記錄,存在gourp by時 order by 無效。 一般解決辦法就是 ,select * from ( select * from order by id) group by 。 因為項目實際中 查詢規則復雜,需要使用到 union 聯合查詢, 另外和關聯查詢,在 laravel4.2中 如果關聯join 多條件時,在union 會出現 最后的結果集不正確。問題是出現在,laravel最后生成 where 表達式時不對。
執行 最后 sql :
SELECT * FROM ( ( SELECT id FROM table_a JOIN table_b ON table_a.id = table_b.t_id (AND table_b.x_id = 1) WHERE id =2 ) UNION ( SELECT id FROM table_c JOIN table_d ON table_c.id = table_d.t_id (AND table_c.x_id = 3) WHERE id = 4 ) ) AS t GROUP BY id
正確解析應該時表達式數組是 [ 1,2,3,4] ,實際查詢laravel 表達式時 結果為[ 1,1,2,3,3,4](忘記,具體是幾個,但是會出現1 和 3 出現多次是真實出現的)
$model_a = DB::table( 'table_a' )->select( 'id' )->join( 'table_b' , function( $query ){ $query->on( 'table_b.a_id' , '=' , 'table_a.id' ) ->where( 'table_b.x_id' , 1) })->where( 'id' , 2 )->orderBy('time','desc');
$model_b = DB::table( 'table_c' )->select( 'id' )->join( 'table_d' , function( $query ){ $query->on( 'table_c.c_id' , '=' , 'table_d.id' ) ->where( 'table_c.x_id' , 3); }) ->where( 'id' , 4 ) ->orderBy('time','desc');
$result = $model_b->union( $model_a );
$data = DB::table( DB::raw("($result->toSql() ) as t"))->mergeBindings( $result->getBindings() )->groupBy( 'id' )->get();
個人解決方案: 1.
獲取2個model表達式的 查詢條件 $model_a->getBindings(); 結果位 [1,2]
$model_b->getBindings(); 結果位 [3,4]
$data = DB::table( DB::raw("($result->toSql() ) as t"))->setBindings(array_merge($model_a->getBindings(),$model_b->getBindings())->groupBy( 'id' )->get();
2. 使用源生sql方式解決。