MySQL 单 DISTINCT 列

标签 mysql

此表包含主机和接口(interface)列UNIQUE 组合 * 编辑:这个表也有一个自动递增的唯一 ID,抱歉我应该在之前提到这个 **

| host....  | interface..... | value      |
+-----------+----------------+------------+
| Host-0    | Interface-15   |    490     |
| Host-2    | Interface-4    |    490     |
| Host-3    | Interface-0    |    495     |
| Host-3    | Interface-7    |    485     |
| Host-5    | Interface-13   |    495     | 
| Host-5    | Interface-17   |    495     |
| Host-10   | Interface-9    |    490     |
| Host-11   | Interface-11   |    495     |
| Host-12   | Interface-9    |    485     |
| Host-12   | Interface-17   |    490     |

我想为 DISTINCT host 按值选择前 10 名

我试过:

SELECT host, interface, value FROM table ORDER BY value DESC LIMIT 10;

| host.... | interface..... | value     |
+----------+----------------+-----------+
| Host-0   | Interface-15   |   490     |
| Host-5   | Interface-17   |   495     |
| Host-5   | Interface-13   |   495     |
| Host-11  | Interface-11   |   495     |
| Host-3   | Interface-0    |   495     |
| Host-0   | Interface-15   |   490     |
| Host-12  | Interface-17   |   490     |
| Host-10  | Interface-9    |   490     |
| Host-2   | Interface-4    |   490     |
| Host-3   | Interface-7    |   485     |
| Host-12  | Interface-9    |   485     |

但我在主机中有重复项。我只需要显示具有最高值的不同主机

例如: Host-5 Interface-17 495 主机12接口(interface)-17490

我也试过:

SELECT
  host,
  interface,
  value
FROM table
GROUP BY host
ORDER BY value DESC
LIMIT 10;

但是,我没有得到具有最高值的主机

最佳答案

您可以通过多种方式做到这一点。这是不存在方式:

SELECT host, interface, value 
FROM table t
WHERE NOT EXISTS (select 1
                  from table t2
                  where t2.host = t.host and t2.value > t.value
                 )
ORDER BY value DESC
LIMIT 10;

这表示:“获取表中具有相同主机但没有更高值的所有行。”

您也可以使用 group by 来做到这一点,使用 group_concat()/substring_index() 技巧:

select host, substring_index(group_concat(interface order by value desc), ',', 1) as interface,
       max(value)
from table t
group by host
order by max(value) desc
limit 10;

关于MySQL 单 DISTINCT 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25484378/

相关文章:

mysql - 选择不同的互斥(基于另一列的值)行

MySQL变量不工作

MySQL 在同一个表中加入两个查询

mysql - 依靠 Rackspace 云服务器备份镜像是处理 mysql 备份的好方法吗?

mysql - 如何在 SQL 中迭代 CASE 语句?

大表的 Mysql 性能

mysql - 将oracle for循环转换为mysql循环

python - 垃圾/ python /MySQL : What is the best approach for saving additional item information in a separate table?

php - Laravel 中带有 where 条件的数据库字段值的总和

mysql - 如果第二个表中的条件为真,则从第一个表中选择 1 条记录(所有引用行均处于事件状态 = 0)