繁体   English   中英

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

[英]Select max and min values in one sql query

我有一个表,该表带有其时间戳记。 现在我需要获取最早的记录和最新的记录

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'];

有什么方法可以优化此代码和完全填充需求,而无需通过特殊查询或存储过程发送两个数据库调用

您可以使用maxmin获取最新和最旧的时间戳记

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM