I want to update the sort_id for all my users. For example, since there are 10 users, I want to specify sort_id from 0-9 respectively. I can do it using foreach in PHP, but it causes a lot of performance and time problems. Is there a method to do it without running each update query again?
UPDATE users SET sort_id=LAST_INSERT_ID(sort_id)+1 WHERE id IN(100,101,102,103,104)
what I really want to do
users
#id - #sort_id
100, 0
101, 1
102, 2
103, 3
104, 4
2
Answers
I don’t know why you want to store redundant data which can be calculated by the value of another column from the same table. Data redundancy leads to data anomalies and corruption and should be always avoided in relational database systems.
If you need sort_id only on client side, just use a simple select.
If you really want to store the sort_id, then use UPDATE with a subquery:
You can use the
row_number()
function:The subquery assigns a sequential number to the rows, which is then used to update the
sort_id
column.