duankuaizhe8257 2014-03-31 08:59
浏览 79
已采纳

在mysql_fetch_array中排序一个特定的值

I have data set with full of data...

 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

I have this php/mysql code to traverse it

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)){}

Now i want to sort $rw in this manner

I have three values

loc=16,SubLoc=2813,beds=1

I want to show same result but show all results in this manner

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

and then rest of results

How this can be done in php?

UPDATED

I want to get these Ids

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

and so on

  • 写回答

2条回答 默认 最新

  • duanchi19820419 2014-03-31 09:23
    关注

    Try that:

    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

    to get other results also without matching then use this:

     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

    EDIT: to include all cases use this:

      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条)

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?