mysql - 在mysql表中选择总和前10名
问题描述
我有如下的 MySQL 表
id, name, postcode, address
在我的表中,邮政编码将是这样的
AX12 3NB
NB76 5BQ
AX23 6NB
AX87 6CZ
我想获得前 10 个邮政编码,比如以 AX 开头的邮政编码出现 3 次
我有 Laravel 项目,想用这种语法做
DB::table('users')
我想获得任何邮政编码前 2 个字母的总数,并且只有前 10 条记录。
谢谢
解决方案
首先,获取所有记录,然后使用 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);
推荐阅读
- javascript - How does stack in Javascript works for parallel function calls?
- rgraph - RGraph - 标签中的自定义 HTML
- python - (自动)python中单变量时间序列数据的异常值校正
- groovy - Scriptrunner - 如何重命名附件文件名
- php - 你能在 PHP echo 中使用表单吗?
- php - 如何修复它我的密码哈希是有效的
- cypress - 在柏树中是否有任何方法可以单独运行 3 个依赖表单?
- c - 将整数分配给取消引用的字符指针
- reactjs - 在 React 中使用 Hook 填充状态
- c# - 对不起,大家。我从 Visual Studio 2019 构建了 Setup.exe。但我尝试安装到另一台 PC/笔记本电脑,但它不起作用