从多行中选择Mysql数据,算术,排序


select Mysql data from multiple rows, arithmetic, sort

我正在从mysql数据库中提取数据。我想加上多次跑步的长度,并根据跑得最远的人的排名进行排序。

    function determineLength($db, $name){
      $getLength = "select length from $db where name = $name and sex = 'male'";
      $gettingLength = mysql_query($getLength);
      while($gotLenth = mysql_fetch_array($gettingLength)){
      more code that calculates total length and returns it as $lengthAccumulator 
      }
      return array('totalLength'=>$lengthAccumulator);
    } 

现在,我有30个不同的男性,他们的名字永远不会改变,我需要提取和排序。我应该如何在没有冗余的情况下为每个人运行mysql代码?我只能这样想-

    $name = john;
    $a = determineLength($db, $name);
    $aLength = $a['totalLength'];
    $name = sam;
    $b = determineLength($db, $name);
    $bLength = $b['totalLength'];
    $name = henry;
    $c = determineLength($db, $name);
    $cLength = $c['totalLength'];
    $name = ted;
    $d = determineLength($db, $name);
    $dLength = $d['totalLength'];

然后存储$aLength、$bLength、$cLength。。。将它们分成一个数组,然后按这种方式进行排序。这似乎是一种错误的方式,更不用说冗余和缓慢了。数据库中有超过4万行的数据,所以尝试这样做会在数据库中运行120多万次?!我可以将一个名称数组传递到函数中,然后在mysql代码中使用ORDERBY长度的DESC吗?

我需要帮助。非常感谢。

    ****the answer below by zane seemed to work to order the runners, but   

使用这种方法,我将如何回应实际排名?我已经把他的精选声明替换成了我上面的声明,但我该如何回应一个人的排名呢?我可以将结果保存到一个数组中,然后回显键吗?

如果我正确理解您的情况,您只需在一条SQL语句中完成即可:

SELECT   name
FROM     $db
GROUP BY name
ORDER BY SUM(length) DESC

所有的东西都已经从结果集中直接排序了。没有程序代码。

上面得到了所有的跑步者,但如果你想得到一组特定的男性跑步者,你可以添加一个WHERE子句,如下所示:

SELECT   name
FROM     $db
WHERE    name IN ('name1', 'name2', 'name3', 'etc...') AND 
         sex = 'male'
GROUP BY name
ORDER BY SUM(length) DESC

要在实际SQL中排名,您可以执行以下操作:

SELECT     name, @rank:=@rank+1 AS rank
FROM       $db
CROSS JOIN (SELECT @rank:=0) val_init
WHERE      name IN ('name1', 'name2', 'name3', 'etc...') AND 
           sex = 'male'
GROUP BY   name
ORDER BY   SUM(length) DESC

然后引用php中的rank列来获取该人员的级别。