简体   繁体   English

SQL结果中的最大和最小PHP函数

[英]Max and min PHP function from SQL result

I'm quite new in PHP dev and I can't find a way to solve my problem. 我是PHP开发人员中的新手,找不到解决我问题的方法。
I have to clean a some data in my Mysql database. 我必须清理Mysql数据库中的一些数据。 I have a date column in my DB full of time periods like 我的数据库中有一个date列,其中充满时间段,例如

-520;-510;0;-500;-530;-599;-499;-510;-490;-500;0;-450 

and I want to extract the min and max value from it, so that I will only have 2 time period left. 我想从中提取最小值和最大值,这样我只剩下2个时间段。

I tried this : 我尝试了这个:

$sql = "SELECT date FROM records WHERE serial = 1";
$requete = mysql_query($sql,$cnx) or die(".mysql_error().");
while($result = mysql_fetch_array($requete))
{
    $res = $result[date];
    $min = min($res);
    $max = max($res);
}

I understand that it can't work because min and max functions are only working with an array but I don't know how to tranform my $result[date] in an new array. 我知道这是行不通的,因为min和max函数仅适用于数组,但是我不知道如何将$result[date]转换为新数组。

Do this in SQL, something like this should work: 在SQL中执行此操作,应如下所示:

$sql = "SELECT MAX( date) as maximum, MIN( date) as minimum
            FROM records 
        WHERE serial = 1
        GROUP BY serial";

Then to retrieve the result, you need one row: 然后,要检索结果,您需要一行:

$requete = mysql_query($sql,$cnx) or die( mysql_error());
$row = mysql_fetch_array($requete);
echo $row['maximum'] . ' ' . $row['minimum'];

assuming that the DB "date" field contains a string of numbers seperated by ; 假设数据库“日期”字段包含一串数字,并以;分隔; like you described then you can use the explode() function to turn that string into an array and then use max() and min() on that array 如您所描述的,您可以使用explode()函数将字符串转换为数组,然后在该数组上使用max()和min()

$arr = explode(";",$string);
$max = max($arr);
$min = min($arr);

if it sa one number per row then do it with SQL like described in the other answer 如果它是每行一个数字,则像另一个答案中所描述的那样使用SQL

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

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