2012-03-29 64 views
3

我試圖讓一個ORDER BY野外作業使用通配符,並已成功:MySQL的ORDER BY字段%

SELECT positions.*, 
     departments.dept_name, 
     departments.dept_url, 
     divisions.dept_name AS div_name 
FROM positions LEFT JOIN departments 
      ON positions.colleague_dept_code = departments.colleague_code 
    LEFT JOIN departments AS divisions 
      ON positions.colleague_div_code = divisions.colleague_code 
WHERE colleague_id = '$colleague_id' 
ORDER BY FIELD(positions.colleague_position_id, 'A%', 'F%', 'T%', 'S%', 'C%') 

colleague_position_id領域有我們的MIS系統生成的文字標識,和我'd喜歡以A開頭的職位首先展示,F展示第二個等,等等。

任何幫助你可以提供將不勝感激。

謝謝!

+0

你可以爲你的職位創建一個單獨的表,並有一個'等級'列嗎?然後,您可以加入您現有的查詢並通過positrion.rank進行訂購。 – 2012-03-29 01:12:11

+0

不可以,因爲不幸的是,每個職位ID是不同的,我們確定職位的唯一方法是基於這封信。沒有任何數字將它們綁在一起 – Pete 2012-03-29 01:20:35

回答

3

這應該給你的大多數控制它:

order by 
    case left(positions.colleague_position_id, 1) 
    when 'A' then 1 
    when 'F' then 2 
    when 'T' then 3 
    when 'S' then 4 
    when 'C' then 5 
    else 6 
    end, positions.colleague_position_id 

這是因爲你可以發送所有不匹配的值到你想要的位置(在這種情況下在最後)。 field()函數將爲0返回不匹配的值,並將它們置於結果集的頂部,甚至在以A開頭的結果集之前。

此外,您還可以按照我在示例中所做的那樣按positions.colleague_position_id進行訂購,因此對於以相同字母開頭的許多positions.colleague_position_id,它們仍將按順序排列。

+1

Mosty,完美的工作!謝謝! – Pete 2012-03-29 01:41:16