如何根据几个标准来决定/查询数据

时间:2014-11-15 06:04:29

标签: mysql sql algorithm

我有表:servers,其中包含我的服务器列表。

---+--------------+---------+----------+
id |  disk_space  | memory  | cpu_core |
---+--------------+---------+----------+
 1 |      100000  |  2048   |   1      |
---+--------------+---------+----------+
 2 |      200000  |  1024   |   2      |
---+--------------+---------+----------+
 3 |      200000  |  2048   |   1      |
---+--------------+---------+----------+
 4 |      100000  |  2048   |   2      |
---+--------------+---------+----------+

如何根据该规格获得最佳服务器(具有多个最大值)?

对于上面的示例,我需要使用id=3获取记录,因为在两个字段(disk_space和memory)中有最大值。

<案例2
---+--------------+---------+----------+
id |  disk_space  | memory  | cpu_core |
---+--------------+---------+----------+
 1 |      100000  |  2048   |   1      |
---+--------------+---------+----------+
 2 |      200000  |  4096   |   4      |
---+--------------+---------+----------+
 3 |      200000  |  2048   |   2      |
---+--------------+---------+----------+
 4 |      400000  |  2048   |   2      |
---+--------------+---------+----------+

这应该返回id = 2

的行

2 个答案:

答案 0 :(得分:0)

我不知道它是否是正确的语法,但这可行。

SELECT * FROM table ORDER BY disc_space DESC,memory DESC,cpu_core DESC LIMIT 1

答案 1 :(得分:0)

我在DB2上工作,所以你可能需要为MYSQL重构这个,但是这会在DB2上做到这一点:

with CTE_MAX_VALUES as (

select max( DISK_SPACE ) as MAX_DISK_SPACE
      ,max( MEMORY )     as MAX_MEMORY
      ,max( CPU_CORE )   as MAX_CPU_CODE
from   SERVERS
)

select     SERVERS.*
from       CTE_MAX_VALUES
cross join SERVERS
order by   case when DISK_SPACE = MAX_DISK_SPACE then 1 else 0 end +
           case when MEMORY     = MAX_MEMORY     then 1 else 0 end +
           case when CPU_CORE   = MAX_CPU_CORE   then 1 else 0 end desc
fetch      first row only

你没有提到如何处理领带。在平局的情况下,如果例如应该在其他列之前选择某个最大列,则可以通过以下方式处理增强的订单:

order by   case when DISK_SPACE = MAX_DISK_SPACE then 1 else 0 end +
           case when MEMORY     = MAX_MEMORY     then 1 else 0 end +
           case when CPU_CORE   = MAX_CPU_CORE   then 1 else 0 end desc
          ,case when CPU_CORE   = MAX_CPU_CORE   then 1 else 0 end desc --tie - 1st choice
          ,case when MEMORY     = MAX_MEMORY     then 1 else 0 end desc --tie - 2nd choice 
          ,case when DISK_SPACE = MAX_DISK_SPACE then 1 else 0 end desc --tie - 3rd choice