【发布时间】:2020-05-29 18:09:29
【问题描述】:
我想要一个包含一组选定用户的列表,我可以在其中查看他们从特定日期开始的点击次数。 Clicks 是一个有几百万行的表,对我来说最合适的块点是大约 250 000 到 500 000 作为块值。 (此 SQL 查询耗时 2.4 秒)
SELECT c.user_id, u.name, count(*) as aantal
from clicks c
join users u on c.user_id = u.id
where c.updated_at > '2020/02/09 20:00' and c.user_id not in (1, 3, 16, 18, 19, 20)
GROUP BY user_id;
对于每个用户的所有点击,此查询是否有效:
$users= User::has('clicks')
->withCount('clicks')
->orderBy('clicks_count', 'desc')
->get()
->whereNotIn('id', [1, 3, 16, 18, 19, 20])
->transform(function ($item) {
// Remove all fields that you don't use inside the view
unset($item->created_at, $item->updated_at, $item->admin, $item->email_verified_at);
return $item;
});
为了获得总点击次数,我发现了这个:
$count = 0;
Click::chunk(500000, function($clicks) use (&$count)
{
$count = $count + count($clicks);
});
我尝试了一些查询,但到目前为止没有任何效果。
我在想这样的事情:
$users = User::whereNotIn('id', [1, 3, 16, 18, 19, 20])->get();
foreach ($users as $user) {
// Here find all CLicks for this user with later then a date with a Chunk
}
但是你会为每个用户遍历所有(几 2-4)百万行,还有其他方法吗?
【问题讨论】: