PHP:获取mysql列中的最高和最低值?

时间:2015-11-14 12:32:49

标签: php mysql

我试图在mysql专栏中获得最高和最低价值,但我想知道这是否可能!

我在官方MYSQL论坛中遇到过这段代码,但我真的不知道如何将这些值作为PHP变量获取!

SELECT
(SELECT `price` FROM mytable ORDER BY `price` LIMIT 1) AS lowest,
(SELECT `price` FROM mytable ORDER BY `price` DESC LIMIT 1) AS highest

基本上我需要做的是从mysql问题创建PHP变量,得到最高值为$hiestprice,最低值为$lowestprice

所以我继续前进,我做了:

$sql = "SELECT
    (SELECT `price` FROM mytable ORDER BY `price` LIMIT 1) AS lowest,
    (SELECT `price` FROM mytable ORDER BY `price` DESC LIMIT 1) AS highest";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query ); // count the output amount
if ($productCount > 0) {
    while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){

$hiestprice = $row['price'];
$lowestprice = $row['price'];

}

}

但这是错误的,当我回复$hiestprice$lowestprice时,我的PHP页面上没有返回任何内容!

有人可以指出我正确的方向吗?

3 个答案:

答案 0 :(得分:6)

首先,您可以优化查询并使用

SELECT MIN(  `price` ) AS  `lowest` , MAX(  `price` ) AS  `highest` FROM  `mytable`

比你可以使用

的价格
$highestprice = $row['highest'];
$lowestprice = $row['lowest']

答案 1 :(得分:2)

当您使用AS lowest后缀时,在php和其他客户端(例如phpmyadmin)中,您将获得此别名lowest

您可以将查询优化为一个选择:

SELECT MIN(`price`) AS `lowest`, MAX(`price`) AS `highest` FROM `mytable`;

并且在php中(对于查询,您的和优化的),您应该通过别名来获取:

<?php

$hiestprice = $row['lowest'];
$lowestprice = $row['highest'];

答案 2 :(得分:1)

$hiestprice = $row['highest'];
$lowestprice = $row['lowest'];

试试这个。

你也应该考虑编辑查询,

SELECT MIN(`price`) AS lowest , MAX(`price`) AS highest FROM  `mytable`

希望这有帮助。