我的目标是展示过去一个月内新记录数量最多的前五名玩家。
是否存在仅使用单个查询的方法,还是需要使用PHP来完成目标?这是我已经完成这个的简化版本(我想这更像是一个性能问题。另外请忽略CodeIgniter;它是多余的):
$res = [];
$q = $this->db1->query('SELECT authid, name FROM table WHERE date BETWEEN NOW() - INTERVAL 30 DAY AND NOW() ORDER BY date DESC');
foreach ($q->result_array() as $row) {
if (isset($res[$row['authid']])) {
$res[$row['authid']]['records'] += 1;
} else {
$res[$row['authid']] = [
'records' => 1,
'name' => $row['name']
];
}
}
arsort($res);
return array_slice($res, 0, 5);
答案 0 :(得分:4)
您需要group by
和order by
以及limit
:
SELECT authid, COUNT(*) as cnt
FROM table
WHERE date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
GROUP BY authid
ORDER BY cnt DESC
LIMIT 5;