【问题标题】:Laravel: Combining the results with UnionAll with countLaravel:将结果与 UnionAll 与计数相结合
【发布时间】:2017-10-19 22:58:05
【问题描述】:

假设我在表 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: (select city,count(*) as aggregate from resume_profiles group by city) union all (从resume_profiles中选择current_location作为城市))

我不知道如何实现这一点

【问题讨论】:

    标签: mysql laravel laravel-5


    【解决方案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();
    

    【讨论】:

      【解决方案2】:

      你需要的是这样的查询

      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": "艾哈迈达巴德", +“聚合”:1, }, {#707 +“城市”:“钦奈”, +“聚合”:1, }, {#685 +“城市”:“加尔各答”, +“聚合”:3, }, {#684 +“城市”:“孟买”, +“聚合”:1, }, {#687 +“城市”:“浦那”, +“聚合”:2, }, ]

      【讨论】:

        【解决方案3】:

        我刚刚对此进行了测试,它可以根据您的需要工作。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-09-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多