首页 > 解决方案 > 在mysql表中选择总和前10名

问题描述

我有如下的 MySQL 表

id, name, postcode, address

在我的表中,邮政编码将是这样的

AX12 3NB
NB76 5BQ
AX23 6NB
AX87 6CZ

我想获得前 10 个邮政编码,比如以 AX 开头的邮政编码出现 3 次

我有 Laravel 项目,想用这种语法做

DB::table('users')

我想获得任何邮政编码前 2 个字母的总数,并且只有前 10 条记录。

谢谢

标签: mysqllaravel

解决方案


首先,获取所有记录,然后使用 PHP 对数组进行排序和缩小。最好的方法是使用原始查询,但由于您在上面说过您不想使用原始查询,因此这是处理它的一种快速方法。

$users = DB::table('users')->get();
$postcodes_array = [];
foreach ($users as $user) {
    $first_two = substr($user->postcode, 0, 2);
    if (isset($postcodes_array[$first_two])) {
        $postcodes_array[$first_two] += 1;
    } else {
        $postcodes_array[$first_two] = 1;
    }
}
arsort($postcodes_array);
$postcodes_array = array_slice($postcodes_array, 0, 10);

推荐阅读