让我们说我在表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 :(选择城市,计数(*)作为来自resume_profiles
组的聚合由city
)union all(从resume_profiles
选择current_location作为城市))
我不知道怎么做到这一点
试试这个:
$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();
你需要的是这样的查询
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, }, ]
我刚刚对此进行了测试,并根据您的需求进行了测试。
$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();