在UNION查询中的orderBy给出了SQLSTATE [42601]错误

时间:2014-11-01 10:43:30

标签: sql postgresql laravel-4 union

注意:使用Lravel 4.1框架

您对POSTGRES DB的我的Sql查询是

$results1 = DB::table('vehicle_brands')
                    ->where('vehicle_brands.caption','ilike', '%'.$_GET['key_word'].'%')
                    ->join('vehicle_manufacturers','vehicle_manufacturers.id', '=', 'vehicle_brands.vehicle_manufacturer_id')
                    ->select('vehicle_brands.*','vehicle_manufacturers.caption AS vm_caption');
                    $results = DB::table('vehicle_brands')
                    ->where('vehicle_manufacturers.caption','ilike', '%'.$_GET['key_word'].'%')
                    ->join('vehicle_manufacturers','vehicle_manufacturers.id', '=', 'vehicle_brands.vehicle_manufacturer_id')
                    ->select('vehicle_brands.*','vehicle_manufacturers.caption AS vm_caption')
                    ->union($results1)
                    ->orderBy('vehicle_brands.caption','ASC')
                    ->get();
                return Response::json(array('status' => true,'data' => $results));

我得到的错误如下:

  

SQLSTATE [42601]:语法错误:7错误:语法错误在或附近   "联合"第1行:... ilike $ 1 order by" vehicle_brands"。" caption" ASC   union sele ... ^(SQL:select" vehicle_brands"。,   #&34; vehicle_manufacturers""字幕" as" vm_caption"从   " vehicle_brands"内部联合" vehicle_manufacturers"上   #&34; vehicle_manufacturers"" ID" =   " vehicle_brands"" vehicle_manufacturer_id"哪里   #&34; vehicle_manufacturers""字幕" ilike%o%order by   #&34; vehicle_brands""字幕" asc union select" vehicle_brands"。,   #&34; vehicle_manufacturers""字幕" as" vm_caption"从   " vehicle_brands"内部联合" vehicle_manufacturers"上   #&34; vehicle_manufacturers"" ID" =   " vehicle_brands"" vehicle_manufacturer_id"哪里   #&34; vehicle_brands""字幕" ilike%o%)

我在查询中做错了什么?

三江源。

1 个答案:

答案 0 :(得分:0)

我使用Laravel 4.1作为框架并使用postgres作为数据库。

我在发布上述问题后进一步研究并找到了我的问题的解决方案,如下所示。

这是一个可以在https://github.com/laravel/framework/pull/3901讨论的错误,讨论也提供了解决方案。

也找到了Stackoverflow解决方案(这与上面相同但是很清楚)

https://stackoverflow.com/a/25722206

我将我的代码转换为如下:

$query1 = DB::table('vehicle_brands')
            ->where('vehicle_brands.caption','ilike', '%'.$term.'%')
            ->join('vehicle_manufacturers','vehicle_manufacturers.id', '=', 'vehicle_brands.vehicle_manufacturer_id')
            ->select('vehicle_brands.*','vehicle_manufacturers.caption AS vm_caption');
        $query2 = DB::table('vehicle_brands')
            ->where('vehicle_manufacturers.caption','ilike', '%'.$term.'%')
            ->join('vehicle_manufacturers','vehicle_manufacturers.id', '=', 'vehicle_brands.vehicle_manufacturer_id')
            ->select('vehicle_brands.*','vehicle_manufacturers.caption AS vm_caption');
        $query = $query1->union($query2);
$items = DB::table(DB::raw("($querySql order by 'caption' 'ASC') as a"))->mergeBindings($query)
                        ->take($limit)
                        ->skip($limit * ($page - 1))
                        ->get();

$term是搜索关键字。

谢谢。