简体   繁体   English

MySQL在PHP栏中的最大价值

[英]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. 我需要在表中获得最大的ID号。 The status is just another column that I think should be unrelated to finding the greatest number in the ID column. 状态只是我认为与ID列中找到最大数字无关的另一列。 What am I doing wrong? 我究竟做错了什么?

If you are looking for the maximum id in the table the query should be: 如果要在表中查找最大ID,则查询应为:

 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. 您的分组依据列将为状态的每个唯一值提供最大ID,如果您按状态分组以获取任何有意义的结果,则还应将其作为选择字段之一。

 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: 如果要从具有最大ID的特定行获取完整数据,则可以执行以下操作:

 $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. 状态只是我认为与ID列中找到最大数字无关的另一列。

The problem is that MAX() is an aggregate function that will return the max id per group as per your GROUP BY clause. 问题在于MAX()是一个聚合函数,它将根据GROUP BY子句返回每个组的最大ID。 So it doesn't make sense to SELECT type, MAX(ID) and then GROUP BY Status . 因此,对SELECT type, MAX(ID)然后再按GROUP BY Status没有意义。 If you want the max id per type, you want GROUP BY type . 如果需要每种类型的最大ID,则需要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 ). 除非在极少数情况下会滥用该功能,否则选择一列(如type )然后再按GROUP BY其他选择(如StatusStatus 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. 有人认为mysql完全允许这种类型的查询是一个错误/错误的功能。

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

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