Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reorder records / rows in a MySQL table

Tags:

sql

mysql

I have the table, that has three columns: ID, Name and ParentID. Let's consider this structure:

ID |   Name   | ParentID
 1     Root       NULL
 2   Parent #1     1
 3   Parent #1     1
 4   Parent #1     1
 5   Parent #1     1
 6   Child  #1     2
 7   Child  #1     2
 8   Child  #1     3
 9   Child  #1     4
 10  Child  #1     5
 11  Child  #1     5

After reordering the rows by a user, the JavaScript on the client-side will send an array with the new order of the rows by their IDs. For example, it can be [4, 10, 2, 3, 11, 1].

What query/queries should I use so that I could change the order of the rows in my MySQL table? I want to get something like this:

ID |   Name   | ParentID
 1     Root       NULL
 9   Child  #1     4
 5   Parent #1     1
 4   Parent #1     1
 3   Parent #1     1
 6   Child  #1     2
 7   Child  #1     2
 8   Child  #1     3
 2   Parent #1     1
 10  Child  #1     5
 11  Child  #1     5
like image 901
Vladyslav Turak Avatar asked Apr 22 '15 09:04

Vladyslav Turak


People also ask

How do I change the order of rows in a MySQL table?

To sort the rows in the result set, you add the ORDER BY clause to the SELECT statement. In this syntax, you specify the one or more columns that you want to sort after the ORDER BY clause. The ASC stands for ascending and the DESC stands for descending.

How do I move rows in MySQL?

You can move rows from one table to another with the help of INSERT INTO SELECT statement.

How do I rearrange SQL?

Using SQL Server Management StudioIn Object Explorer, right-click the table with columns you want to reorder and select Design. Select the box to the left of the column name that you want to reorder. Drag the column to another location within the table.

How do I reorder columns in MySQL?

[FIRST | AFTER col_name]: FIRST or AFTER can be used to change a column's order. FIRST is used if we want to make our column the first column of a table; AFTER keyword is used if we're going to place our column after a specific column (col_name).


1 Answers

In my view, you can't do it without having an extra column order

You will have to create a new column order for this purpose.

Then update the table as array is passed.

foreach($passed_array as $order => $val){
 $q = "Update table SET  `order` = $order WHERE ID = $val";
 // run query here
}

EDIT

And when displaying data at frontend, select query will be like

"SELECT * FROM table `Order` BY `order` ASC"
like image 196
Umair Ayub Avatar answered Sep 21 '22 11:09

Umair Ayub