MySQL Single DISTINCT列

时间:2014-08-25 10:56:25

标签: mysql

此表包含主机和接口列UNIQUE combination * 编辑:此表还有一个自动递增的唯一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     |

但我在主持人中有重复。我只需要显示具有最高值的独特主机

例如: 主机-5接口-17 495 主机12接口-17 490

我也尝试过:

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

但是,我没有获得价值最高的主机

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT host, interface, value
FROM table t1
WHERE value = (SELECT MAX(value) 
    FROM table t2 
    WHERE t2.host = t1.host)
AND interface = (SELECT 
    t3.interface
    FROM table t3 
    WHERE t3.value = t1.value
    AND t3.host = t1.host limit 1)
ORDER BY value DESC LIMIT 10;

答案 1 :(得分:1)

您可以通过各种方式执行此操作。这是not exists方式:

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;