如何在php中显示mysql数据库的最高价值

时间:2013-10-02 05:32:05

标签: php mysql

这是mysql表

---------------------------------------------
id | date       | name     |  amount 
---------------------------------------------
1  | 2013-01-31 | abcd     | 200.000 
2  | 2013-02-28 | apple    | 95.000
3  | 2013-03-31 | bannna   | 30.000
4  | 2013-04-30 | computer | 5.000
5  | 2013-05-31 | mobile   | 500.000 
6  | 2013-06-30 | mouse    | 2.000
7  | 2013-07-31 | led tv   | 25000.000
---------------------------------------------

如何找到此表的最高金额

我想在php页面中这样的结果 最高金额第一

Date       |  Name  | Amount
2013-07-31 | LED TV | 25000.000
2013-05-31 | Mobile | 500.000
2013-01-31 | Abcd   | 200.000
2013-02-28 | Apple  | 95.000

我该怎么做才能帮我解决这个问题 感谢

我正在使用此代码,但它没有显示我的结果类型。

<?php
$username = "root";
$password = "";
$hostname = "localhost"; 

//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password) 
 or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";

//select a database to work with
$selected = mysql_select_db("car",$dbhandle) 
  or die("Could not select examples");



//execute the SQL query and return records
$result = mysql_query("SELECT MAX( amount ) AS amount FROM table5");

//fetch tha data from the database 
while ($row = mysql_fetch_array($result)) {
   echo "Date:".$row{'date'}." Name:".$row{'name'}."Amount: ". //display the results
   $row{'amount'}."<br>";
}
//close the connection
mysql_close($dbhandle);
?>

6 个答案:

答案 0 :(得分:4)

由于您的属性amountvarchar(字符串)字段,因此您需要先将属性转换为int

SELECT * FROM table5 ORDER BY CAST(amount as SIGNED INTEGER) DESC

如果您只运行以下查询

SELECT * FROM table5 ORDER BY amount DESC

它会将列排序为字符串,结果将是

---------------------------------------------
id | date       | name     |  amount 
---------------------------------------------
2  | 2013-02-28 | apple    | 95.000
4  | 2013-04-30 | computer | 5.000
5  | 2013-05-31 | mobile   | 500.000
3  | 2013-03-31 | bannna   | 30.000
6  | 2013-06-30 | mouse    | 2.000
1  | 2013-01-31 | abcd     | 200.000 
7  | 2013-07-31 | led tv   | 25000.000
---------------------------------------------

答案 1 :(得分:2)

您的查询现在是

SELECT MAX( amount ) AS amount FROM table5

该查询表示:获取table5的一个最大值

Instaed,应该是

SELECT * FROM table5 ORDER BY amount DESC

该查询表示:获取所有值,从最高到最低排序。

<强>更新: 上述查询适用于numeric列,而不是varchars,因为OP显然需要。

答案 2 :(得分:2)

您的以下查询仅返回'table5'

的金额字段中的最大值
SELECT MAX( amount ) AS amount FROM table5

但是你的需求与之不同,而不是你应该编写像

这样的查询
SELECT * FROM table5 ORDER BY amount DESC

以上查询将按照从最高到低的顺序返回table5中的总行数,这就是您要查找的内容。

答案 3 :(得分:1)

SELECT * FROM table5 ORDER BY amount DESC

答案 4 :(得分:1)

使用此查询:

SELECT `date`, `name`, `amount` from `table` order by `amount` desc LIMIT 4

因为您的查询仅显示最大值(仅一条记录)

SELECT MAX( amount ) AS amount FROM table5

答案 5 :(得分:1)

MAX显示列中的最高记录。它应该是这样的

SELECT * FROM your_table_name ORDER BY amount DESC