Laravel:将结果与UnionAll结合使用

时间:2017-05-19 18:04:14

标签: mysql laravel laravel-5

让我们说我在表resume_profiles

中有2列
   current_location      city
    | Chennai  |    | Kolkatta   |
    | Mumbai   |    | Ahmaedabad |
    | Pune     |    | Kolkatta   |
    | Kolkatta |    | Pune       |

我需要将这些结果合并到一个SET中,所以我会有这样的事情:

   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 :(选择city,count(*)作为resume_profiles组中的聚合{{1} } all all(从city选择current_location作为城市))

我不知道如何实现这个

3 个答案:

答案 0 :(得分:2)

尝试这样做:

  $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();

答案 1 :(得分:0)

您需要的是像这样的查询

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

这是dbfiddle

我没有看到使用Eloquent或QueryBuilder表达这种优雅方式。只需使用原始查询

$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,
     },
   ]

答案 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();