2012-07-16 36 views
0

我试图获取分配给特定子类别 (id = 9)的配置文件名称。当我运行下面的代码时,我得到了我想要的配置文件,但对于某些 原因,foreach循环中的ORDER BY子句不按字母顺序排列它们的名称 。相反,它们的排列方式与“子类别”表中 “配置文件”字段中的顺序相同(配置文件的ID以逗号分隔)。 例如,如果在子类别[“剖面”]我已经”,5,1,2' 轮廓名称将按照以下顺序显示 :在MySQL中的顺序子句不在foreach循环内工作

  1. 资料与ID = 5
  2. 资料ID为= 1
  3. 资料与ID = 2

我使用的爆炸()函数来获取“子类别” 表内的各轮廓的ID,然后使用该ID从检索其信息'profile'表使用 foreach循环内的查询。

我在这里错过了什么吗?谢谢你的帮助。

这里是我的代码:

<?php 
$subcategories=mysql_query("select * from subcategories where id='9'"); 

while ($subcategories = mysql_fetch_array($subcategories)) 

{ 
$profiles = $subcategories['profiles']; 
$profiles = explode(',', $profiles); 

     foreach ($profiles as $p) 
     { 
     $all_places = mysql_query("select * from profile where id='$p' and active='1' order by name asc"); 

      while ($profile = mysql_fetch_array($all_places)) 
      { 

       echo $profile['name'];     

      } 

     } 

} 
?> 
+0

如果没有'ORDER BY'子句(如果被排除),它工作正常吗? – Lion 2012-07-16 09:02:12

+0

是的,它工作正常。 – 2012-07-16 09:26:52

回答

1

那么为什么你的结果不按名称排序的原因是因为你检索与一个新的SQL查询中的每个配置文件在你的foreach循环为$配置文件。在您的情况下,如果有效,您最终将得到3个SQL查询,每个查询返回1个配置文件。因此,当声明“order by”子句时,它在每个查询中按名称排序,每个查询只包含1个结果。

是否使用IN语句适合您?例如。

<?php 
$subcategories=mysql_query("select * from subcategories where id='9'"); 

while ($subcategories = mysql_fetch_array($subcategories)) 

{ 

//i assume $subcategories['profiles'] are integers separated by comma as mentioned 
$profiles = $subcategories['profiles']; 

       $all_places = mysql_query("select * from profile where id IN ($profiles) and active='1' order by name asc"); 

        while ($profile = mysql_fetch_array($all_places)) 
        { 

         echo $profile['name'];     

        } 

} 
?> 
+0

我刚想出了另一种方法来做到这一点。我没有从子类别表中选择配置文件ID,而是使用MySQL语句中的LIKE选择了具有该子类别ID的所有配置文件。 $子类别= '9'; $ subcategories1 = mysql_query(“select * from profile where LIKE'%$ subcategories%'AND active ='1'order by name asc”);我也删除了内部的foreach和while循环,因为它们不再需要。现在看起来工作正常,谢谢。 – 2012-07-16 09:34:18

+0

它似乎现在正常工作,除了一个小问题:如果我有子类别ID 9和19上述查询将返回两个。任何想法如何克服这一点? – 2012-07-16 10:00:03

+0

问题解决了,我尝试了你的建议和它的工作。我只需要从$ profiles字符串中删除第一个逗号,因为它导致了一个问题。谢谢你的帮助! – 2012-07-16 11:29:22