子查询中“id”的顺序发生了变化?

时间:2011-09-15 05:41:04

标签: mysql sql sql-order-by

我有这个查询

SELECT bul.id 
FROM bul 
WHERE id  IN (SELECT hotid AS parentid 
FROM likehot 
WHERE hotid IN (SELECT id 
FROM bul 
WHERE  DATE  >= '1315976410') 
GROUP BY hotpid 
ORDER BY COUNT( hotid ) DESC )

当我对这个内部查询进行判断时

SELECT id 
FROM bul 
WHERE  DATE  >= '1315976410') 
GROUP BY hotpid 
ORDER BY COUNT( hotid ) DESC

我得到了

parentid
3655
3656
3622
3644

当我运行整个查询时,我得到了

parentid
3656
3655
3622
3644

我真的不明白为什么ids的顺序改变了?

解决方案: -

<?php
 $query_hotpress_like = "SELECT hotid AS parentid FROM likehot WHERE hotid IN (SELECT id FROM bul WHERE  DATE  >= '" . (time() - (24 * 60 * 60)) . "') GROUP BY hotid ORDER BY COUNT( hotid ) DESC";
                $exe_hotpress_like = execute_query($query_hotpress_like, true, "select");
                $temp_like1 = array();
                foreach ($exe_hotpress_like as $kk => $exe_like) {

                    $temp_like1[] = "'" . $exe_like['parentid'] . "'";
                }
                $temp_like = str_replace(",''", "", implode(',', $temp_like1));

                $query_hotpress = "SELECT bul.id,photo_album_id,eventcmmnt_id,link_url,youtubeLink,link_image,id, mem_id, subj, body, bul.date,parentid, from_id, visible_to,image_link,post_via FROM bul WHERE id IN ($temp_like) ORDER BY FIELD(id,$temp_like ) LIMIT 5";

                ?>

execute_query()是用于获取查询结果的内置函数。

2 个答案:

答案 0 :(得分:2)

发生这种情况是因为IN运算符顺序并不重要。

如果需要对外部查询进行排序 - 排序外部查询。

答案 1 :(得分:2)

由于您没有为“整个”查询指定订单,因此数据库可以按任何顺序返回行。您获得的具体顺序是使用IN运算符时查找行的结果。

在您的其他查询中,您自己指定订单,因此数据库必须遵守该订单。