php - 获取数据库的前 3 个计数

标签 php mysql

我需要一个查询来从数据库中获取前 3 个计数,但使用 max 只会从中获取前 3 个计数。如何获得前 3 名的计数?

count

30
29
29
28
28
28
27
26
25

SELECT count FROM tableName WHERE count = max($count) LIMIT 30 //doesn't work because max only get the top first count.

预期结果

30
29
29
28
28
28

最佳答案

子查询选择最高的 3 个不同值。在本例中,它们是 30、29 和 28,外部查询选择具有这些计数之一的所有行。

select `count` from tablename
where `count` in (
    select distinct `count`
    from tablename
    order by `count` desc
    limit 3
)

顺便说一下,count 是一个保留字,您应该尽量避免将其用作列名。

关于php - 获取数据库的前 3 个计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32811364/

相关文章:

mysql - Windows 10 家庭版(和专业版)上存在 mysql 容器问题的 Docker 工具箱

java - 是否可以在同一系统上同时运行两个服务器?或者当 XAMPP/WAMP 未运行时如何在 Eclipse 中执行 MySQL 查询?

mysql - 具有相同 id 的多条记录通过 Cursor 将其设为 NULL

python - MySQL cur.execute with 格式

PHP mysql 使用 groupby 计数行不起作用?

php - mysql 创建一个带有有序子菜单的菜单

php - 删除 CSV 中的第一行,然后保存覆盖现有文件

php - 如何使用 Laravel 管理数据库表中的 'order' 列?

php - 在 php/pdo 和三个表中创建一个 friend 列表

php - 事件调度程序计算结果的 if 条件