Sort table, using loop in MySQL with SELECT and UPDATE with NATURAL ORDER

倾然丶 夕夏残阳落幕 提交于 2019-12-25 02:47:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!