2017-05-19 3 views
1

でUnionAllで結果を組み合わせることで、私は、単一のセットにこれらの結果を結合する必要がある、だから私はこのようなものを持っていると思い、私はテーブルresume_profilesにLaravel:数

current_location  city 
    | Chennai | | Kolkatta | 
    | Mumbai | | Ahmaedabad | 
    | Pune  | | Kolkatta | 
    | Kolkatta | | Pune  | 

を2列を持っているだけと言うことができます:

City  Aggregate 
| Chennai | | 1 | 
| Mumbai  | | 1 | 
| Pune  | | 2 | 
| Kolkatta | | 3 | 
| Ahmaedabad | | 1 | 

問合せ:

$current_locations = ResumeProfile::selectRaw('current_location as city'); 

ResumeProfile::selectRaw('city,count(*) as aggregate') 
      ->unionAll($current_locations) 
      ->groupBy('city')->get(); 

上記のクエリを使用すると、例外を含む以下のクエリが表示されます。

SQLSTATE [21000]:カーディナリティ違反:1222使用されたSELECTステートメントの列数が異なります(SQL :(select city、count(* ))cityによってresume_profilesグループからの骨材として労働組合のすべて(resume_profilesから都市としてCURRENT_LOCATIONを選択))

私はこれを行う試すこの

答えて

1

を達成する方法はありませんません:

$current_locations = ResumeProfile::selectRaw('current_location as city'); 

$subquery=ResumeProfile::selectRaw('city') 
     ->unionAll($current_locations); 

    DB::table(DB::raw("({$subquery->toSql()}) AS s")) 
     ->selectRaw('s.city,count(*) as aggregate') 
      ->groupBy('s.city')->get(); 
0

は何が必要ここで私はこの使用して雄弁またはQueryBuilderを表現するエレガントな方法が表示されないdbfiddle

あるこの

SELECT city, COUNT(*) aggregate 
    FROM (
    SELECT current_location AS city FROM resume_profiles 
    UNION ALL 
    SELECT city FROM resume_profiles 
) q 
GROUP BY city 

のようなクエリです。ただ、生のクエリ

$sql = <<<'SQL' 
SELECT city, COUNT(*) aggregate 
    FROM (
    SELECT current_location AS city FROM resume_profiles 
    UNION ALL 
    SELECT city FROM resume_profiles 
) 
GROUP BY city 
SQL; 

$cities = DB::select($sql); 

ティンカー、それを使用します。

 
>>> DB::select($sql); 
=> [ 
    {#706 
     +"city": "Ahmaedabad", 
     +"aggregate": 1, 
    }, 
    {#707 
     +"city": "Chennai", 
     +"aggregate": 1, 
    }, 
    {#685 
     +"city": "Kolkatta", 
     +"aggregate": 3, 
    }, 
    {#684 
     +"city": "Mumbai", 
     +"aggregate": 1, 
    }, 
    {#687 
     +"city": "Pune", 
     +"aggregate": 2, 
    }, 
    ] 
0

を私はこれをテストし、それはあなたのニーズに応じて動作します。

$cityInfo = DB::table(DB::raw('(select current_location as city from resume_profiles union all select city from resume_profiles) as resume_profiles')) 
    ->select(DB::raw('city, count(city) as total')) 
    ->groupBy('city') 
    ->get();