![](/img/trans.png)
[英]Select rows based on the highest value in a column of an other table in MySQL & PHP
[英]How do you return rows from Mysql based on highest value in table column?
我有一個功能,應該在數據庫中搜索最高的“得分”。 Db的結構如下:
----------------------------------------
| id | UrlId | Article | Score |
----------------------------------------
我可以正確獲得最高分數,但是我不知道如何根據最高分數返回完整的對象。 我不願意遍歷整個表並測試'score'的值以查看哪個值最高(盡管我鍵入時我仍然懷疑自己正在這樣做),因為該數據庫可能具有10000條記錄。 我確信這很簡單,但是我有“愚蠢的今天我不能動腦筋”,還有誰知道更優雅的解決方案嗎?
我的最終結果必須是這樣的:如果有4個UrlId; s具有相同的最高得分,則用戶需要查看:
UrlId example1 20(分數)
UrlId example2 20(分數)
UrlId example3 20(分數)
UrlId example4 20(分數)
所有其他結果將不會顯示。
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;
}
SELECT fieldlist
FROM `tableName`
WHERE `score` = (SELECT MAX(`score`) FROM `tableName`)
您不能使用查詢嗎?
SELECT *
FROM table_name
ORDER BY score
DESC LIMIT 1;
如果您需要多個分數,則可以使用子查詢:
SELECT *
FROM table_name
WHERE score =
(SELECT score
FROM table_name
ORDER BY score
DESC LIMIT 1;
);
嘗試這個。
$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;
在這里, ORDER BY Score DESC
提取具有最高得分的第一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.