sql >> Base de Datos >  >> RDS >> Mysql

Ordenar tabla, usando bucle en MySQL con SELECCIONAR y ACTUALIZAR

SELECT @p:=0, @parent:=0;
UPDATE page p1
JOIN
( SELECT title, 
  CASE WHEN @parent<>parent_id THEN @p:=0 ELSE @p:[email protected]+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

Si sus pares (parent_id,title) no son únicos, use su clave principal como condición de unión; deberá agregarla para seleccionar entre paréntesis.