php从数据库中选取ID在数组中存在的记录,并按数组中的顺序排列?

fire-rain 2012-04-17 08:46:41
比如$arr={"5","7",1"","10","3","8"},要从数据库中选取ID值为5,7,1,10,3,8的记录,并且按这个顺序排列。
...全文
251 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
fire-rain 2012-04-19
  • 打赏
  • 举报
回复
[Quote=引用 7 楼 的回复:]

咳咳, 麻烦把php部分和mysql互换后(先php再mysql)再测一下 :)


引用 6 楼 的回复:

//我的测试结果显示PHP排序速度优于MySQL排序速度,刷新了NN次只有1次是PHP慢过MySQL的,请大家也测试一下吧

<?php
//date_default_timezone_set('Asia/Shanghai');
$link = mysql_con……
[/Quote]

这个可以有,,
helloyou0 2012-04-18
  • 打赏
  • 举报
回复
咳咳, 麻烦把php部分和mysql互换后(先php再mysql)再测一下 :)


[Quote=引用 6 楼 的回复:]

//我的测试结果显示PHP排序速度优于MySQL排序速度,刷新了NN次只有1次是PHP慢过MySQL的,请大家也测试一下吧

<?php
//date_default_timezone_set('Asia/Shanghai');
$link = mysql_connect('localhost','root');
mysql_select_db('test');

$timeS1……
[/Quote]
jaksmine 2012-04-18
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

SQL code
SELECT * FROM table WHERE id IN(5,7,1,10,3,8) ORDER BY FIND_IN_SET(id,'5,7,1,10,3,8');
[/Quote]

FIND_IN_SET,学习了,没用过
andyxl 2012-04-18
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

真棒! 这个find_in_str用得好

引用 1 楼 的回复:

SQL code
SELECT * FROM table WHERE id IN(5,7,1,10,3,8) ORDER BY FIND_IN_SET(id,'5,7,1,10,3,8');
[/Quote]

not str , find_in_set


(表很大的情况)这样的sql效率可能会很低,建议查询出来后用代码来排序
K-dash 2012-04-18
  • 打赏
  • 举报
回复
//我的测试结果显示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;
}
helloyou0 2012-04-17
  • 打赏
  • 举报
回复
真棒! 这个find_in_str用得好

[Quote=引用 1 楼 的回复:]

SQL code
SELECT * FROM table WHERE id IN(5,7,1,10,3,8) ORDER BY FIND_IN_SET(id,'5,7,1,10,3,8');
[/Quote]
代码如诗 2012-04-17
  • 打赏
  • 举报
回复
SELECT * FROM table WHERE id IN(5,7,1,10,3,8) ORDER BY FIND_IN_SET(id,'5,7,1,10,3,8');

21,881

社区成员

发帖
与我相关
我的任务
社区描述
从PHP安装配置,PHP入门,PHP基础到PHP应用
社区管理员
  • 基础编程社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧