我从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 ...存储到一个数组中并按这种方式排序。 它似乎是错误的做法,更不用说冗余和缓慢。数据库中有超过40k行的数据,所以尝试这样做会在数据库中运行超过1.2万次?!我可以将一组名称传递给函数,然后在mysql代码中使用ORDER BY长度DESC吗?
我需要帮助。谢谢!
****the answer below by zane seemed to work to order the runners, but
如何使用此方法回显实际排名?我已将他的选择陈述替换为我上面的陈述,但我如何回应一个人的等级呢?我可以将结果保存到数组中然后回显键吗?
答案 0 :(得分:6)
如果我理解你的情况,你可以在一个单独的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
列中的人员等级。