1

I am trying to sort data from on this page: http://www.excelwrestling.com/sortbymostwinsbyweight.php

I want the table to be ordered by Weight and then the name with most wins in that weight. Also, I would like to add one more column showing the number of wins for that wrestler.

This is what I having from looking at tutorials but they are not being ordered correctly:

$query="SELECT *,Winner, COUNT(*) as count FROM results GROUP BY Winner ORDER BY Weight ASC ";
$result=mysql_query($query);

Thanks!

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
                ) ;

An index on (Weight, Winner) will help efficiency of the query.


You may get the correct result with this query, too, but I do not recommend it as it uses some non-standard features and behaviours of MySQL, and therefore could break in the future:

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

You're ordering just by winner, when you say your requirements are by 'most wins'. That means you should have:

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

Note that I'm assuming you want the weights in ascending order, and wins in descending order.

于 2012-07-01T22:20:06.537 に答える