问题
Some long time ago I asked HERE to help with sorting the table. And user "piotrm" gave an exellent sollution, thanks to him! It works perfect!
SELECT @p:=0, @parent:=0;
UPDATE page p1
JOIN
( SELECT title,
CASE WHEN @parent<>parent_id THEN @p:=0 ELSE @p:=@p+1 END as position,
@parent:=parent_id as parent_id
FROM page
ORDER BY parent_id, title DESC ) p2
ON p1.title = p2.title AND p1.parent_id = p2.parent_id
SET p1.position = p2.position
Now I need this code to be upgraded with NATURAL SORTING. I mean it STILL needs to be sorted THE SAME WAY, but when it meets TITLE STARTING WITH '2', '13', '1', '26', it has to be ordered NOT '1', '13', '2', '26'; BUT '1', '2', '13', '26'.
I apologize for lack of knowledge in SQL, but I really need your help! Thank you a lot!
回答1:
SELECT @p:=0, @parent:=0;
UPDATE page p1
JOIN
( SELECT title,
CASE WHEN @parent<>parent_id THEN @p:=0 ELSE @p:=@p+1 END as position,
@parent:=parent_id as parent_id
FROM page
ORDER BY LENGTH(title), title, parent_id ASC ) p2
ON p1.title = p2.title AND p1.parent_id = p2.parent_id
SET p1.position = p2.position
来源:https://stackoverflow.com/questions/23031633/sort-table-using-loop-in-mysql-with-select-and-update-with-natural-order