我可以使用子查询代替搜索MAX()?

时间:2016-11-14 08:19:50

标签: mysql

我有表'master_log',我存储了所有操作的所有数据。每个记录通过'm_id'连接在一起:

m_id | value_type_id | value
------------------------------------------
1    | room          | ONE
1    | temperature   | 23
1    | humidity      | 55
1    | timestamp     | 2016-11-01 00:00:01
2    | room          | TWO
2    | timestamp     | 2016-11-01 00:10:51
2    | temperature   | 24
3    | room          | ONE
3    | temperature   | 24
3    | timestamp     | 2016-11-01 00:18:24
------------------------------------------

我需要ONE室的最高温度。我现在使用的查询是:

SELECT MAX(value)
FROM master_log
WHERE value_type_id = 'temperature'
    AND m_id IN (SELECT m_id
                    FROM master_log
                    WHERE value = 'ONE')

当我开始测量时,查询很快,但现在有数百万条记录,它不是太快,我寻找最快的方法。好吗?

1 个答案:

答案 0 :(得分:0)

E.g:

SELECT m_id
     , MAX(CASE WHEN value_type_id = 'room' THEN value END) room
     , MAX(CASE WHEN value_type_id = 'temperature' THEN value END) temperature
     , MAX(CASE WHEN value_type_id = 'humidity' THEN value END) humidity
     , MAX(CASE WHEN value_type_id = 'timestamp' THEN value END) timestamp
  FROM master_log 
 GROUP 
    BY m_id 
HAVING room = 'ONE' 
 ORDER 
    BY temperature DESC 
 LIMIT 1;

...但是,适当的索引,马丁的解决方案会更快