2010-01-26 77 views
5

我正忙於編寫一個從數據庫獲取數據的PHP應用程序,但我需要按照特定順序獲取數據。使用mySql以特定順序獲取數據

我的查詢看起來如下

$sql = "select id,title,type from campaigns where id=$cid order by type"; 

現在我的問題是,這些是不同類型的 'GC', 'MJ', 'MU', 'MS', 'MW', 'MX',」 GS',我希望MX總是選擇最後,因此應該總是在行的末尾。所以首先選擇其他人,然後選擇MX。我希望這是有道理的。

回答

15

您可以按這樣的:

ORDER BY IF (type = 'MX', 1, 0), type 
+0

+1,比我的更好,更完美的解決方案;) – 2010-01-26 13:07:08

+0

+1,這比我的解決方案肯定更聰明。 – 2010-01-26 13:07:15

+2

哇..我甚至沒有可能的最遙遠的線索。 – Erik 2010-01-26 13:09:42

0
$sql = "select id,title,type from campaigns where id=$cid and type != 'MX' order by type 
union 
select id,title,type from campaigns where id=$cid and type = 'MX'"; 
0

多少行,你和你的查詢選擇?看起來只有一個(我假設id是唯一的...),所以排序順序沒有影響。

除此之外,排序順序應該按照它按字母順序執行的操作,MX將成爲列表中的最後一個。

1
(select id,title,type from campaigns where id=$cid and type <> 'MX' order by type) 
UNION 
(select id,title,type from campaigns where id=$cid and type ='MX') 
0

其他的SQL方法都拋出了。既然你已經用php標記了這個,我還會指出你可以使用usort函數來定義一個自定義比較函數,以供排序算法使用。

// returns 1 if lhs > rhs, returns 0 if lhs == rhs, returns -1 if lhs <rhs 
function customCompare($lhsRow, $rhsRow) 
{ 
    $lhsType = $lhsRow['type'] 
    $rhsType = $lhsRow['type'] 
    // special case code so that 'MX' is always > then anything (except for another MX) 
    if ($lhsType == 'MX') 
    { 
      if ($rhsType == 'MX') 
      { 
       return 0; 
      } 
      else 
      { 
       return 1; 
      } 
    } 

    // return 1 if lhs > rhs 
    if ($lhsType > $rhsType) 
    { 
     return 1; 
    } 
    else if ($rhsType < $lhsType) 
    { 
     return -1; 
    } 
    else 
    { 
     return 0; 
    } 
} 

$rows = /*perform query without ORDER*/ 
usort($rows, "customCompare"); 
0

您可能需要使用UNION

SELECT id, title, type 
FROM campaigns 
WHERE id={$cid} 
AND type != 'MX' 
ORDER BY type 

UNION 

SELECT id, title, type 
FROM campaigns 
WHERE id={$cid} 
AND type == 'MX' 

並運行它作爲一個查詢。

0
... 
order by case when type = 'MX' then 1 else 0 end, type 

將移植到其他數據庫(如PostgreSQL的)