在一个sql查询中选择最大值和最小值

时间:2014-12-05 04:17:24

标签: php mysql sql stored-procedures

我有一个包含时间戳的记录的表。现在我需要获得最早的记录和最新的记录

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需求而不发送两个数据库调用,通过特殊查询或存储的进程

2 个答案:

答案 0 :(得分:5)

您可以使用maxmin来获取最新和最早的时间戳

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

答案 1 :(得分: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