2014-03-31 33 views
0

我有數據具有完整的數據集...SORT在mysql_fetch_array一個特定的值

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 

+0

爲什麼不在mysql中排序呢? –

+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 
+0

這裏有一個問題,我想檢查一下loc和subLoc是否匹配,然後它應該在最上面......這裏不是這種情況 – user3244721

+1

你想做所有的情況嗎?檢查這個http://sqlfiddle.com/#!2/7af8b/3 –

+0

寶貝,你是真正的GURU – user3244721

0

與爲了嘗試

ORDER BY SubLoc=16 DESC,loc, beds

+1

這不起作用,Subloc具有更高的值,然後需要在最上面的期望記錄。 – Tuim

+0

這將給我loc = 15 first..which我不想...我需要等於在排序 – user3244721

+0

那麼你想要的不是秩序? – Sadikhasan