简体   繁体   中英

MySQL biggest value in column PHP

I need to get the biggest value of a certain column. This is my code that I got on a turorial.

$query = "SELECT type, MAX(ID) FROM sessions GROUP BY Status"; 

$result = mysql_query($con, $query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
echo "The biggest session ID is " .$row['MAX(ID)'];
echo "<br />";
}

I need to get the greatest ID number in the table. The status is just another column that I think should be unrelated to finding the greatest number in the ID column. What am I doing wrong?

If you are looking for the maximum id in the table the query should be:

 SELECT max(ID) from sessions;

Your group by column will give your the maximum id for each unique value of Status, and if you are grouping by status to get any meaningful results you should also have that as one of the selection fields like.

 SELECT Status, max(ID) from sessions group by Status

将您的MAX(ID)函数调用别名化为查询中的列名;

SELECT type, MAX(ID) AS max_id FROM sessions GROUP BY status

If you want to get the full data from the specific row with the biggest id, you can do:

 $query = "SELECT type, MAX(ID) 
           FROM sessions 
           WHERE ID = MAX(ID) 
           GROUP BY Status";

The status is just another column that I think should be unrelated to finding the greatest number in the ID column.

The problem is that MAX() is an aggregate function that will return the max id per group as per your GROUP BY clause. So it doesn't make sense to SELECT type, MAX(ID) and then GROUP BY Status . If you want the max id per type, you want GROUP BY type .

Except in the very rare advanced situation where the feature can be abused, it never makes sense to select a column (like type ) but then GROUP BY something else (like Status ). In fact, most databases do not allow you to do this; some people consider it a bug/bad feature that mysql allows this type of query at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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