更改我的查询以从表列中获取最大值和最小值


change my query to get the max and min values from a table column

我有以下功能:

function get_max_weight()
{
   global $db;
   $query = "SELECT weight FROM products WHERE weight=(select max(weight) from products)";
   $result = mysql_query($query);
   $results = mysql_fetch_row($result);
   return $results[0];
}

我使用nouislider和$maxweight = get_max_weight()来定义滑块范围的上限。我现在想从相同的函数中获得最小重量。

因此,我的问题是:1)如何更改上面的查询以获得最大值和最小值;以及2)如何在页面上输出这些值?

您不需要子查询,只需要:

$query = "SELECT MIN(weight) AS minweight, MAX(weight) AS maxweight FROM products";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
return $row;

这将返回一个关联数组,如:

[ 'minweight' => 10, 'maxweight' => 50 ]

我不明白为什么你需要一个子查询,看起来你只提取了一行,那么为什么你需要查询来返回多行呢?

单个查询可以返回最小值和最大值,例如:

SELECT MIN(weight) AS min_weight
     , MAX(weight) AS max_weight
  FROM products

至于从函数返回这两个值,我认为您可以从函数返回单个数组对象。


PHPmysql函数已弃用。有两个可行的接口可用:mysqliPDO。(凭良心讲,我不能给出一个包括对不推荐使用的mysql_函数的调用的答案。)

使用:

$query = "SELECT max(weight), min(weight) FROM products";
$execute = mysql_query($query);
$result = mysql_fetch_row($execute);
return $result;

为了得到吹嘘的

echo $result[0]; //gives you max weight.
echo $result[1]; //gives you min weight