1

我正在尝试从此页面上对数据进行排序: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);

谢谢!

4

2 回答 2

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 ;
于 2012-07-01T22:38:17.910 回答
-1

winner当您说您的要求是“最胜”时,您只是按 订购。这意味着您应该拥有:

SELECT ...
FROM ...
GROUP BY Winner
ORDER BY Weight ASC, count DESC
         ^^^^^^^^^^^^^---- order by the aggregate results.

请注意,我假设您希望权重按升序排列,并按降序排列。

于 2012-07-01T22:20:06.537 回答