Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing field order dynamically in mysql

In my project I made many changes in database and at some time I need to re-assign order to some table in my database. so, I want is. I have following table.

id     name     address     order
1      vijay    mumbai      2
3      ram      delhi       4
4      ravi     pune        5
5      rutul    surat       8
9      vipul    agra        11

And I want to update it from mysql query...like

id     name     address     order
1      vijay    mumbai      0
3      ram      delhi       1
4      ravi     pune        2
5      rutul    surat       3
9      vipul    agra        4

So I want is my order field to update from 0 to plus one and on and on... How to do that I have no idea...I try but I am also not near to the solution. How to do that? Please help me.

like image 343
Divyesh Jesadiya Avatar asked Jun 24 '17 09:06

Divyesh Jesadiya


People also ask

How do I change the order of rows in MySQL?

An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.

How to modify columns IN MySQL?

The syntax to modify a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name MODIFY column_name column_definition [ FIRST | AFTER column_name ]; table_name. The name of the table to modify.

Does order of columns matter in MySQL?

column order does not matter. This is purely a convenience feature. just to allow you to restructure your database table the way you like after it has been created.

How to add column IN MySQL table?

To add a column in a table in MySQL, we can use ALTER command with add column command. First, let us create a table with columns Id and Name. After that, we will add column name Age and Address with the help of ALTER command. The following is the query to create a table.


1 Answers

You can use following query:

SET @orderid = -1;    
update yourTableName set `order` = (@orderid:=@orderid+1)
order by id asc

EDIT:

In codeIgniter you can do like following:

$this->db->query("SET @orderid = -1");
$this->db->query("update table_name set `order` = (@orderid:=@orderid+1) order by id asc");
like image 182
B. Desai Avatar answered Oct 13 '22 14:10

B. Desai