I need to regenerate all primary key numbers from zero and keep previous amount in ex column but the query doesnt work :
update mh_product AS p,(select p.id AS oldid,row_number() OVER (order by p.id asc)-1 AS newid from p) AS bp set p.id=bp.newid,p.ex=bp.oldid
I have this table
+-----------+----------+
| id | ex |
+-----------+----------+
| 24 | 0 |
| 25 | 0 |
| 27 | 0 |
| 29 | 0 |
| 30 | 0 |
+-----------+----------+
and need to convert to this :
+-----------+----------+
| id | ex |
+-----------+----------+
| 0 | 24 |
| 1 | 25 |
| 2 | 27 |
| 3 | 29 |
| 4 | 30 |
+-----------+----------+
2
Answers
I actually suggest considering not doing this update, the reason being that if your data changes again in the future, you might be forced to run the update multiple times.
Instead, consider just querying with a select to view the data you want:
The query you provided is almost correct, but there is a small syntax error that needs to be corrected. The table alias p is being used inside the subquery select p.id…, but p has not been defined yet. Instead, you should use the subquery’s table alias bp to reference the id column:
Please use this as the solution.