简体   繁体   English

SQL-返回最大列值

[英]SQL - Return Max Column Value

I have been searching for how to do this but I didn't find anything useful! 我一直在寻找如何执行此操作,但没有发现任何有用的信息!

So I have the following table with the following columns: 所以我有下表,其中包含以下列:

ID | USER | COMMENTS
---------------------
1  | John | 20
2  | Sara | 32
3  | Peter| 10

What I want to do is to pick the user with most comment. 我想做的就是选择评论最多的用户。 I'm using: 我正在使用:

<?php
$usermaxresult = mysql_query("SELECT MAX(comments) FROM users"); 
while ($usermaxrow = mysql_fetch_array($usermaxresult)) {
$max = "MAX(comments)";
echo "$usermaxrow[$max]";
}
?>

But that would only return the number of max comments, not the user with the max comments. 但这只会返回最大评论数,而不会返回具有最大评论的用户。

---- WORKED! ----努力! THANKS FOR THE COMMENTS, CODE (it is in portuguese because I'm portuguese) 感谢评论,代码(是葡萄牙语,因为我是葡萄牙语)

$usermaxuploads = mysql_query("SELECT MAX(uploads) as max_count FROM login");
$usermaxuploadsrow = mysql_fetch_array($usermaxuploads);
$maxvar = $usermaxuploadsrow["max_count"];

$usermaxresult = mysql_query("SELECT * from login WHERE uploads = '$maxvar' ");
$usermaxrow = mysql_fetch_array($usermaxresult);
echo $usermaxrow['usuario'];

It should give you what you need: 它应该给您您所需要的:

SELECT MAX(comments) as tot, user FROM users;

Where tot will be the number of comments and user will be the relative user. 其中tot将是评论数,而user将是相对用户。

Yoy can use an ALIAS in the query to your MAX() function to be able to call it later with given name. Yoy可以在对MAX()函数的查询中使用ALIAS ,以便以后可以使用给定名称调用它。

$usermaxresult = mysql_query("SELECT MAX(comments) as max_count, user FROM users"); 

Now you can print with 现在您可以使用

echo $usermaxrow['max_count'];
echo $usermaxrow['user'];

I don't know if I understand the problem wrongly or just other answers were wrong. 我不知道我是错误地理解了问题还是其他答案是错误的。 How is SELECT MAX(comments) as max_count, user FROM users returns the users with the most comment? SELECT MAX(comments) as max_count, user FROM users如何SELECT MAX(comments) as max_count, user FROM users返回评论最多的用户? It returns the number of the highest comment and the first user (which might not be the user with the most comment). 它返回最高评论数和第一个用户(可能不是评论最多的用户)的编号。 Shouldn't the below query be the correct one? 以下查询不正确吗?

SELECT user, comments FROM users ORDER BY comments DESC LIMIT 0, 1

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

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