我正在尝试对此页面上的数据进行排序:http://www.excelwrestling.com/sortbymostwinsbyweight.php
我希望按重量排序表格,然后在该重量下获得最多胜利的名称。另外,我想再增加一列,显示该摔跤手获胜的次数。
这是我从教程中看到的,但它们没有被正确排序:
$query="SELECT *,Winner, COUNT(*) as count FROM results GROUP BY Winner ORDER BY Weight ASC ";
$result=mysql_query($query);
谢谢!
答案 0 :(得分:0)
SELECT ww.*
FROM
( SELECT Weight, Winner, COUNT(*) AS Wins
FROM results
GROUP BY Weight, Winner
) AS ww
JOIN
( SELECT DISTINCT Weight
FROM results
) AS dw
ON ww.Weight = dw.Weight
AND ww.Winner =
( SELECT r.Winner
FROM results AS r
WHERE r.Weight = dw.Weight
GROUP BY r.Winner
ORDER BY COUNT(*) DESC
LIMIT 1
) ;
(Weight, Winner)
上的索引将有助于提高查询效率。
您也可以通过此查询获得正确的结果,但我不建议使用它,因为它使用了MySQL的一些非标准功能和行为,因此将来可能会中断:
SELECT Weight, Winner, Wins
FROM
( SELECT Weight, Winner, COUNT(*) AS Wins
FROM results
GROUP BY Weight, Winner
ORDER BY Weight, Wins DESC
) AS ww
GROUP BY Weight ;
答案 1 :(得分:-1)
当你说你的要求是“最多的胜利”时,你只是按winner
订购。这意味着你应该:
SELECT ...
FROM ...
GROUP BY Winner
ORDER BY Weight ASC, count DESC
^^^^^^^^^^^^^---- order by the aggregate results.
请注意,我假设您希望权重按升序排列,并按降序获胜。