在mysql_fetch_array中排序一个特定的值

时间:2014-03-31 08:59:03

标签: php mysql arrays sorting

我的数据集充满了数据......

 Id  |  loc    |SubLoc    |beds
 1      15       5803      1
 2      15       5803      1
 3      16       2813      1
 4      16       2813      2
 5      16       2830      1
 6      20       2020      4
 7      19       2513      3

我有这个php / mysql代码来遍历它

select id,loc,SubLoc,beds from table  where id != 144  AND price > 140000 AND price < 210000 AND category_id=1

while($rw = mysql_fetch_array($rs2)){}

现在我想以这种方式对$ rw进行排序

我有三个值

loc=16,SubLoc=2813,beds=1

我想显示相同的结果,但以这种方式显示所有结果

1- having loc==16 on top then
2- having SubLoc = 2813 then
3- having beds  = 1

然后是其他结果

如何在php中完成这项工作?

已更新

我想获得这些ID

3 as it matches 3 parameters
4 as it matches 2 parameters
5 as it matches 2 parametrs
1 as it matches 1 parameter

等等

2 个答案:

答案 0 :(得分:1)

试试:

select id,loc,SubLoc,beds from table1
where loc = 16 or subloc = 2813 or beds =1
order by 
   case when loc = 16      then 0 
        when subloc = 2813 then 1
        when beds = 1      then 2 end asc

DEMO

获得其他结果也没有匹配,然后使用它:

 select id,loc,SubLoc,beds from table1
 order by 
     case when loc  = 16     then 0 
          when subloc = 2813 then 1
          when beds = 1      then 2 
          else 3 end asc

DEMO

编辑以包含所有案例:

  select id,loc,SubLoc,beds from table1
  order by 
  case when loc = 16 and subloc=2013 and beds = 1 then 0 
       when loc = 16      and subloc = 2813       then 1
       when loc = 16      and beds = 1            then 2
       when subloc = 2813 and beds = 1            then 3
       when loc = 16                              then 4 
       when subloc = 2813                         then 5
       when beds = 1                              then 6
       else 7 end asc

答案 1 :(得分:0)

尝试订购

ORDER BY SubLoc=16 DESC,loc, beds