我有一个表,其中包含表示树结构的数据,其中一列表示行在分层树中的位置。每个级别用-分隔。
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中对此数据进行数字排序?
发布于 2011-06-29 02:31:56
我认为你最好的办法就是把数据转换成可以自然排序的东西。如果你的树形结构总是少于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)https://stackoverflow.com/questions/6507862
复制相似问题