Ini*_* EC 82 count distinct laravel eloquent
所以我试图获取查询中不同pid的数量,但返回的值是错误的.
这就是我尝试做的事情:
$ad->getcodes()->groupby('pid')->distinct()->count()
Run Code Online (Sandbox Code Playgroud)
什么返回值"2",而它应返回的值应为"1".
作为一种解决方法,我这样做:
count($ad->getcodes()->groupby('pid')->distinct()->get())
Run Code Online (Sandbox Code Playgroud)
什么工作正常,返回"1"
是否有任何规则,count和distinct不能在同一个查询中?我发现解决方法有点"沉重",我想让原始查询工作:(
小智 96
以下应该有效
$ad->getcodes()->distinct('pid')->count('pid');
Run Code Online (Sandbox Code Playgroud)
And*_*rew 22
一个更通用的答案可以节省我的时间,并希望其他人:
不起作用(返回所有行的计数):
DB::table('users')
->select('first_name')
->distinct()
->count();
Run Code Online (Sandbox Code Playgroud)
修复:
DB::table('users')
->distinct()
->count('first_name');
Run Code Online (Sandbox Code Playgroud)
Zoo*_*oon 16
其他人遇到这个帖子,而没有找到其他建议吗?
根据具体的查询,可能需要不同的方法.在我的情况下,我需要计算a的结果GROUP BY,例如
SELECT COUNT(*) FROM (SELECT * FROM a GROUP BY b)
Run Code Online (Sandbox Code Playgroud)
或使用COUNT(DISTINCT b):
SELECT COUNT(DISTINCT b) FROM a
Run Code Online (Sandbox Code Playgroud)
在经历了一些令人费解之后,我意识到这两款都没有内置的Laravel功能.因此,最简单的解决方案是使用DB::raw该count方法.
$count = $builder->count(DB::raw('DISTINCT b'));
Run Code Online (Sandbox Code Playgroud)
请记住,请勿groupBy在致电前使用count.groupBy如果您需要它来获取行,您可以稍后申请.
您可以使用以下方式根据您的需要获取唯一数据,如下所示,
$data = $ad->getcodes()->get()->unique('email');
$count = $data->count();
Run Code Online (Sandbox Code Playgroud)
希望这会奏效。
I had a similar problem, and found a way to work around it.
The problem is the way Laravel's query builder handles aggregates. It takes the first result returned and then returns the 'aggregate' value. This is usually fine, but when you combine count with groupBy you're returning a count per grouped item. So the first row's aggregate is just a count of the first group (so something low like 1 or 2 is likely).
So Laravel's count is out, but I combined the Laravel query builder with some raw SQL to get an accurate count of my grouped results.
For your example, I expect the following should work (and let you avoid the get):
$query = $ad->getcodes()->groupby('pid')->distinct();
$count = count(\DB::select($query->toSql(), $query->getBindings()));
Run Code Online (Sandbox Code Playgroud)
If you want to make sure you're not wasting time selecting all the columns, you can avoid that when building your query:
$query = $ad->select(DB::raw(1))->getcodes()->groupby('pid')->distinct();
Run Code Online (Sandbox Code Playgroud)