简体   繁体   中英

Change id values of all rows in table STARTING from a specific number

I have 1000 rows in a table..

I'm getting the last and next available id (to start from)

$latest_id = ("SELECT * FROM `vehicles` WHERE ID = (SELECT MAX(ID) FROM `vehicles`)");

What I'm trying to achieve is when clicking on a button, to change the id value of all 1000 rows + to start from the $latest_id

So NOW is:

id 1 = car 1
id 2 = car 2
id 3 = car 3
...

AFTER

id 1001 = car 1
id 1002 = car 2
id 1003 = car 3
...

Can someone help me with the sql query please.

You could write an update statement that cross joins the table with a subquery that computes the maximum value, and then add the maximum value to each id :

update vehicles v
inner join (select max(id) id from vehicles) vmax
set v.id = vmax.id + v.id

Demo on DB Fiddle

Initial content of the table:

id | car  
-: | :----
 1 | car 1
 2 | car 2
 3 | car 3
 4 | car 4

After running the query:

id | car  
-: | :----
 5 | car 1
 6 | car 2
 7 | car 3
 8 | car 4

Use an UPDATE statement with a JOIN

UPDATE vehicles as v
JOIN (SELECT MAX(id) AS maxid
      FROM vehicles) AS x
SET v.id = v.id + x.maxid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM