日期:2014-05-17 浏览次数:20474 次
SELECT * FROM table WHERE id IN(5,7,1,10,3,8) ORDER BY FIND_IN_SET(id,'5,7,1,10,3,8');
------解决方案--------------------
//我的测试结果显示PHP排序速度优于MySQL排序速度,刷新了NN次只有1次是PHP慢过MySQL的,请大家也测试一下吧
<?php
//date_default_timezone_set('Asia/Shanghai');?
$link = mysql_connect('localhost','root');
mysql_select_db('test');
$timeS1 = microtime();
$sql = "SELECT * FROM `lean` WHERE id IN(5,7,1,10,3,8) ORDER BY FIND_IN_SET(id,'5,7,1,10,3,8')";
//for($i = 1, $i <= 100, $++){
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
}
//}
$timeE1 = microtime();
echo '由数据库自行处理的起止时差为: '.($timeE1 - $timeS1).'<br/>';
//释放译一下php的内存先,免得因为前面的变量影响了效率
unset($timeS1);
unset($timeS2);
unset($link); //已经自动设定了活动数据库了,当前调试不用传递这个,所以把它也释放了吧
unset($sql);
unset($result);
unset($row);
//////////////////////
$timeS2 = microtime();
$sql = "SELECT * FROM `lean` WHERE id IN(5,7,1,10,3,8)";
$result = mysql_query($sql);
$data = array();
$i = 0;
while($row = mysql_fetch_array($result))
{
$data[$row['id']] = $row;
$i++;
}
$r = sortdata($data, array(5,7,1,10,3,8));
$timeE2 = microtime();
echo '由PHP处理的起止时差为: '.($timeE2 - $timeS2);
echo '<pre>排序结果<br/>';
print_r($r);
echo '</pre>';
//排序函数
function sortdata($arr,$order){
$r = array();
$i = 0;
foreach($arr as $key => $value){
$r[$order[$i]] = $value;
$i++;
}
return $r;
}