2017-03-09 88 views
0

我想選擇不同sensornodes的不同MAX(值)。我的問題是,WHERE ... IN ...子句的工作原理與許多邏輯「OR」類似,但我需要每個sensornode的MAX($ measure)。我知道如何用循環做到這一點,但我認爲有一個更好的解決方案來做到這一點。根據陣列選擇不同的MAX(值)

這是數據庫的表「測量」:

ID   humidity temperature date  time  sensornode 
---------- ---------- ----------- ---------- ---------- ---------- 
1   22.00%  18.00C  06/03/2017 13:07:18 WSN1  
2   22.00%  18.00C  06/03/2017 13:08:19 WSN2  
3   34.00%  21.00C  06/03/2017 13:09:19 WSN3  
4   21.00%  20.00C  06/03/2017 13:10:19 WSN4 

查詢應不會停這樣

$measure //is either 'temperature' or 'humidity', depends on the users input. 
$sensornode // is a string which is converted with the implode-function from an array which includes the selected 'sensornodes' of the users input 
$sql_query = "SELECT MAX($measure) AS $measure 
    FROM measurement 
    WHERE sensornode IN ('$sensornode')"; 
$data = executeQuery($sql_query, $measure); 

回答

0

要獲得每個傳感器節點,使用分組的最大值:

SELECT sensornode, 
     max(temperature) 
FROM measurement 
GROUP BY sensornode; 

要限制到某些傳感器節點,只需添加一個地址:

SELECT sensornode, 
     max(temperature) 
FROM measurement 
WHERE sensornode IN ('WSN1', 'WSN2', ...) 
GROUP BY sensornode;