2012-03-28 107 views
1

我目前有一個簡單的MySQL選擇與order by名爲postcodes列。這些郵編是英國。MySQL排序英國郵政編碼

它目前正在按此順序輸出:SE1, SW1, SE10, SE11, SE2, SW2, SE3。我知道使用ABS()會糾正數字排序,但我不確定在這種情況下我該怎麼做,因爲有字母和數字。

我想在下面的順序來顯示它們:
SE1, SE2, SE3 SE10, SE11, SW1, SW2

感謝您的幫助。

+0

可能重複http://stackoverflow.com/questions/153633/natural-sort-in-mysql ) – 2012-03-28 18:00:48

+1

你忘了SW1W,EC1A等......這會造成更多問題...... GiroBank GIR 0AA,BFPO ...所以你甚至不能使用數字。這可能會比其他任何事情都更好。 – Ben 2012-03-28 20:08:19

回答

2

您可以在表格中添加一些額外的列以在其中包含片段,並使用第三列進行排序以返回訂單。例如:

PostCodeTable 
|---------------------------------------------| 
|postCode| codePart1 | codePart2 | codePart3 | 
|char() | char() | int()  | whatever() | 
|---------------------------------------------| 
| SE1 | SE  | 1   |   | 
| SW1 | SW  | 10  |   | 
| SE10 | SE  | 10  |   | 
| SE11 | SE  | 11  |   | 
| SE2 | SE  | 2   |   | 
| SW2 | SW  | 2   |   | 
| SE3 | SE  | 3   |   | 
|---------------------------------------------| 

您的查詢可能是:

Select 
    postCode 
from 
    PostCodeTable 
order by 
    codePart1, 
    codePart2 
    // etc etc as needed. 
[自然排序在MySQL(的
+0

由於交付點的數量,這是如何解決[細分](http://en.wikipedia.org/wiki/London_postal_district#High-density_districts)區域的問題的? SW1A,SW1E,SW1H等 – Ben 2012-07-07 10:24:37

+0

@Ben我不知道有多少個字母+數字+字母+數字的組合(因此codePart3),但如果將它們分成單獨的組,則可以輕鬆地按它們排序按正確的順序返回主要部分。 – Fluffeh 2012-07-07 10:29:54

相關問題