2011-06-28 93 views
2

我有一個表格,其中一列表示樹狀結構的數據,其中一列指示行在分層樹中的位置。每個級別用-分隔。以數字順序排列非數字層次字符串

1 
1-1 
2 
2-1 
2-2 
2-2-1 
2-2-2 
2-2-2-1 

樹是爲了檢索簡單地與在該列的ORDER BY。當任何級別的項目超過10個時,這個數值會下降,因爲該列按字母順序排序。 MySQL在3之前排序10

Actual result: 

1 
1-10 
1-3 
2 

Desired result: 

1 
1-3 
1-10 
2 

可能有任何數量的值的深度級別。

是否可以在MySQL中對數據進行數值排序?

回答

2

我認爲你最好的辦法是將數據轉換成自然排序的東西。如果你的樹結構總是少於99個孩子,你可以創建一個像下面這樣的函數。您只需在排序函數中使用「GetTreeStructureSort(columnName)」。 (如果你有3位數字的可能性,你可以調整這是更直觀。)

CREATE FUNCTION GetTreeStructureSort 
(
    -- Add the parameters for the function here 
    @structure varchar(500) 
) 
RETURNS varchar(500) 
AS 
BEGIN 

    DECLARE @sort varchar(500) 

    -- Add a hyphen to the beginning and end to make all the numbers from 1 to 9 easily replaceable 
    SET @sort = '-' + @structure + '-' 

    -- Replace each instance of a one-digit number to a two-digit representation 
    SELECT @sort = REPLACE(@sort, '-1-', '-01-') 
    SELECT @sort = REPLACE(@sort, '-2-', '-02-') 
    SELECT @sort = REPLACE(@sort, '-3-', '-03-') 
    SELECT @sort = REPLACE(@sort, '-4-', '-04-') 
    SELECT @sort = REPLACE(@sort, '-5-', '-05-') 
    SELECT @sort = REPLACE(@sort, '-6-', '-06-') 
    SELECT @sort = REPLACE(@sort, '-7-', '-07-') 
    SELECT @sort = REPLACE(@sort, '-8-', '-08-') 
    SELECT @sort = REPLACE(@sort, '-9-', '-09-') 

    -- Strip off the first and last hyphens that were added at the beginning. 
    SELECT @sort = SUBSTRING(@sort, 2, LEN(@sort) - 2) 

    -- Return the result of the function 
    RETURN @sort 

END 

這將轉換這些結果:

1 
1-10 
1-3 
2 

成這樣:

01 
01-03 
01-10 
02 

我用以下代碼測試了這個:

DECLARE @something varchar(255) 
set @something = '1-10-3-21' 

SELECT dbo.GetTreeStructureSort(@something) 
+0

用零填充數字<10正是我所需要的。當它被指出時很明顯。謝謝你這樣一個非常詳細的答案。 – drewm

相關問題