user3244721
user3244721

Reputation: 754

SORT a specific value in 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

Upvotes: 0

Views: 128

Answers (2)

echo_Me
echo_Me

Reputation: 37233

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

Upvotes: 1

Sadikhasan
Sadikhasan

Reputation: 18600

Try with order

ORDER BY SubLoc=16 DESC,loc, beds

Upvotes: 0

Related Questions