2014-12-05 188 views
2

我有一個記錄了它的時間戳的表。現在我有一個要求,通過發送緩慢起伏兩臺數據庫調用,以獲得最老的記錄和最新記錄在一個SQL查詢中選擇最大值和最小值

9/10/2014 6:54 
9/10/2014 6:53 
9/10/2014 6:51 
9/8/2014 8:09 
9/8/2014 7:00 
9/5/2014 7:38 
9/5/2014 3:57 
9/5/2014 3:51 
9/4/2014 11:09 
9/4/2014 8:39 

目前我這是怎麼獲得這些處理

$new_timestamp = mysql_query("SELECT TIMESTAMP FROM $rectable ORDER BY TIMESTAMP DESC LIMIT 1"); 
$col_old = mysql_fetch_assoc($new_timestamp); 
$old = $col_new['TIMESTAMP']; 

$new_timestamp1 = mysql_query("SELECT TIMESTAMP FROM $rectable ORDER BY TIMESTAMP ASC LIMIT 1"); 
$col_new = mysql_fetch_assoc($new_timestamp1); 
$new = $col_new['TIMESTAMP']; 

有什麼辦法來優化這個代碼和fullfiill要求,而無需發送兩個數據庫調用,througha特殊查詢或存儲proceedure

回答

5

您可以使用maxmin獲得最新和最古老的時間戳

select max(timestamp), min(timestamp) from mytable 
+0

對不起,從同一張桌子! – 2014-12-05 04:26:31

+0

您需要使用大寫的「TIMESTAMP」,並且在TIMESTAMP上創建索引也會有所幫助。 – Tom 2014-12-05 04:28:37

1

嘗試用UNION

select TIMESTAMP as old FROM $rectracktable ORDER BY TIMESTAMP DESC LIMIT 1 
union all 
select TIMESTAMP as new FROM $rectable ORDER BY TIMESTAMP ASC LIMIT 1 
+0

對不起它從同一個表 – 2014-12-05 04:26:05

+0

如果你有相同的表還將努力。但是,在這種情況下,@FindTree的解決方案更加優雅。我以爲你有兩張不同的桌子。 – 2014-12-05 04:27:09