Mysql orderBy最常出现但返回所有行
我基本上是根据结果中出现最多的Mysql orderBy最常出现但返回所有行,mysql,laravel,eloquent,Mysql,Laravel,Eloquent,我基本上是根据结果中出现最多的item\u id对我的收藏进行排序 比如,;我得到了一个包含以下数据的表格: +----+---------+---------+---------+---------+ | id | item_id | column2 | column3 | column4 | +----+---------+---------+---------+---------+ | 1 | 12 | Hi | DataHere| MoreData| | 2 |
item\u id
对我的收藏进行排序
比如,;我得到了一个包含以下数据的表格:
+----+---------+---------+---------+---------+
| id | item_id | column2 | column3 | column4 |
+----+---------+---------+---------+---------+
| 1 | 12 | Hi | DataHere| MoreData|
| 2 | 12 | Hi | DataHere| MoreData|
| 3 | 14 | Hi | DataHere| MoreData|
| 4 | 13 | Hi | DataHere| MoreData|
| 5 | 12 | Hi | DataHere| MoreData|
| 6 | 21 | Hi | DataHere| MoreData|
+----+---------+---------+---------+---------+
我将如何使用一个简单的MyData::get()
model&accessor访问初始表
我已尝试执行以下操作,但只能返回项目id
和计数
,我需要返回所有列,仅按最频繁的项目id
排序
MyData::select(\DB::raw('item_id'), \DB::raw('count(*) as count'))->having('item_id', '>', '0')->groupBy('item_id')->orderBy('count', 'desc')->get();
我的预期结果是:
+----+---------+---------+---------+---------+
| id | item_id | column2 | column3 | column4 |
+----+---------+---------+---------+---------+
| 1 | 12 | Hi | DataHere| MoreData|
| 2 | 12 | Hi | DataHere| MoreData|
| 5 | 12 | Hi | DataHere| MoreData|
| 6 | 21 | Hi | DataHere| MoreData|
| 3 | 14 | Hi | DataHere| MoreData|
| 4 | 13 | Hi | DataHere| MoreData|
+----+---------+---------+---------+---------+
您可以在DB.raw内部进行查询,例如:
DB::select(DB::raw(“从程序p中选择p.name,part.*,其中p.id=part.id”)代码>这应该可以:
$table = app(MyData::class)->getTable();
MyData::selectRaw("*, (select count(*) from $table t where t.item_id = $table.item_id) as count")
->orderBy('count', 'DESC')
->get();
您可以将第一行和$table
替换为实际的表名。和*
,选择您真正想要选择的字段
事实上,如果您不需要选择中的计数
,您可以执行以下操作:
$table = app(MyData::class)->getTable();
MyData::orderByRaw("(select count(*) from $table t where t.item_id = $table.item_id) DESC")
->get();