2013-06-04 65 views
0

我有精密組件的表像通過從MySQL表中抽樣記錄獲取記錄 - 選擇最接近的值?

TimeStamp  | Feild1  | Feild 2 
-------------------------------------- 
1902909002 | xyddtz  | 233447 
1902901003 | xytzff  | 233442 
1902901105 | xytzdd  | 233443 
1902909007 | xytzdd  | 233443 
1902909909 | xytsqz  | 233436 

現在我想查詢並獲取記錄,如時間戳= 1902909002約或1902901003大約OR ... 我想我記錄這曾經是最接近每個歷時間到那個時代

我寫的東西:

string sqlQuery = "SELECT TimeStamp, FwdHr, W FROM Meter_Data WHERE (TimeStamp <= "+timeSt[0].ToString(); 
        for (int i = 1; i < timeSt.Count; i++) 
        { 
         sqlQuery = sqlQuery + " OR TimeStamp <= " +timeSt[i].ToString() ; 
        } 

        sqlQuery=sqlQuery+ ") AND MeterID = @meterID AND DeviceID = @deviceID ORDER BY TimeStamp"; 

這是返回null並且如果從日期和時間有很大的差異或者的將是成千上萬。任何身體都可以提供更好的方法嗎?

回答

0

你可以應用範圍?我的意思是這樣的:

var max=timeSt.Max(); 
var min=timeSt.Min(); 


var sqlString= string.Format(@" 
SELECT 
    TimeStamp, 
    FwdHr, 
W 
    FROM 
    Meter_Data 
WHERE 
    TimeStamp BETWEEN {0} AND {1} 
    AND MeterID = @meterID AND DeviceID = @deviceID 
ORDER BY 
    TimeStamp",min,max);