Adrian Pop :
I need to update column value that is auto increment. For example :
id | value |
---------------
1 | abc |
2 | def |
16 | sdfs |
361 | dsffs |
I need to transfer it to
id | value |
---------------
1 | abc |
2 | def |
3 | sdfs |
4 | dsffs |
For count of all values of that table. Also need to mansion that there are 3 foreign keys on this table for column id
, and when I'm trying to use this query to update column value it fails with duplicate error even though there's no record with this value on any of those tables
set @row_number = 0;
UPDATE
cms_page AS page,
(
SELECT
(@row_number := @row_number + 1) AS id,
page_id
FROM
cms_page
ORDER BY page_id
) AS new_id
SET
page.page_id = new_id.id
Gordon Linoff :
I strongly recommend that you do not do this. However, one simple method uses two updates. Presumably the ids are numbers and never negative. So:
update cms_page
set page_id = - page_id;
set @row_number = 0;
update cms_page
set page_id = (@row_number := @row_number + 1)
order by page_id desc; -- remember, it is now negative
If you have cascading update
constraints -- which are necessary for this to really work for referring tables -- then everything will be updated twice. Be sure you have enough log space!
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=346848&siteId=1