SELECT fieldlist
FROM `tableName`
WHERE `score` = (SELECT MAX(`score`) FROM `tableName`)
How do you return rows from Mysql based on highest value in table column?
質問
I have a function that is supposed to search the db for the highest 'score'. The Db is structured like this:
----------------------------------------
| id | UrlId | Article | Score |
----------------------------------------
I can get the highest score correctly, but I do not know how to return the full object based on the highest score. I am reluctant to loop through the entire table and test the values of 'score' to see which is the highest (although as I type that I suspect I am doing it anyway) because the db will potentially have 10000's of records. I am sure that this is dead simple, but I have "the dumb and I cant brain today" Does anyone know a more elegant solution?
My end result would have to be something like this: if there are 4 UrlId;s with the same top score, the user would need to see:
UrlId example1 20(score)
UrlId example2 20(score)
UrlId example3 20(score)
UrlId example4 20(score)
all other results would not be displayed.
function gethappiestBlog() {
$happiestBlogs = /* This is the data that I loop through, this is correct */
$happinessArray = array();
foreach($happiestBlogs as $happiestBlog) {
$happinessArray[]= $happiestBlog->Score;
}
$maxHappy = max($happinessArray);
echo $maxHappy;
}
解決
他のヒント
Couldn't you use a query?
SELECT *
FROM table_name
ORDER BY score
DESC LIMIT 1;
If you need multiple scores, you could then use a subquery:
SELECT *
FROM table_name
WHERE score =
(SELECT score
FROM table_name
ORDER BY score
DESC LIMIT 1;
);
Try this.
$dbh=new PDO(DSN,USERNAME,PASSWORD);
$stmt=$dbh->prepare("SELECT * FROM TABLE_NAME ORDER BY Score DESC");
$stmt->execute();
while($happiestBlog=$stmt->fetch(PDO::FETCH_OBJ)):
echo $happiestBlog->Score;
endwhile;
Here ORDER BY Score DESC
fetch the the row first ehich has highest Score.