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
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.
You can move rows from one table to another with the help of INSERT INTO SELECT statement.
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.
[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).
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With