Skip to content

Instantly share code, notes, and snippets.

@albabar
Last active November 27, 2015 09:24
Show Gist options
  • Select an option

  • Save albabar/2268a080f2d94386b7cd to your computer and use it in GitHub Desktop.

Select an option

Save albabar/2268a080f2d94386b7cd to your computer and use it in GitHub Desktop.
Reorder a table based on some column.
SELECT x.id,
x.position,
x.title,
x.created_at
FROM (SELECT t.id,
t.title,
t.created_at,
@rownum := @rownum + 1 AS position
FROM posts t
JOIN (SELECT @rownum := 0) r
ORDER BY t.created_at) x;
UPDATE comments c
LEFT JOIN (
SELECT t.id,
t.nid,
t.post_id,
t.created_at,
@rownum := @rownum + 1 AS position
FROM comments t
JOIN (SELECT @rownum := 0) r
ORDER BY t.created_at) x
ON c.id = x.id
SET c.nid = x.position;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment