首页
学习
活动
专区
圈层
工具
发布

MySQL单列
EN

Stack Overflow用户
提问于 2014-08-25 10:56:25
回答 2查看 63关注 0票数 1

这个表有主机列和接口列UNIQUE combination *编辑:这个表还有一个自动递增的唯一id,对不起,我应该在前面提到这一点

代码语言:javascript
复制
| 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位

我试过:

代码语言:javascript
复制
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

我也尝试过:

代码语言:javascript
复制
SELECT
  host,
  interface,
  value
FROM table
GROUP BY host
ORDER BY value DESC
LIMIT 10;

但是,我不会得到价值最高的主机

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-08-25 11:05:22

你可以用不同的方式做这件事。下面是not exists的方法:

代码语言:javascript
复制
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()技巧来完成此操作:

代码语言:javascript
复制
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;
票数 1
EN

Stack Overflow用户

发布于 2014-08-25 10:59:10

试试这个:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25484378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档