I am using the sample Northwind DB and would like to INSERT a new product for every discontinued product and renaming the new product with an appended ‘_v2’. Problem is I would like to specify a new ProductID (for a table that would not have ProductID as autoIncrement). How can I have it get the largest ProductID number and increment it.
I tried this:
INSERT INTO `products2`( `ProductName`, `ProductID`, `SupplierID`, `CategoryID`, `QuantityPerUnit`, `UnitPrice`, `UnitsInStock`, `UnitsOnOrder`, `ReorderLevel`, `Discontinued`)
SELECT CONCAT(p.ProductName, '_V2'), (SELECT MAX(p2.ProductID) FROM products2 p2) + p.ProductID, p.SupplierID, p.CategoryID, 30, p.UnitPrice * 2, 10, 20, 2, 'n'
FROM products2 p
WHERE p.Discontinued = 'y';
and problem is it seems to retrieve the the MAX productID and reusing it over and over again, giving all my new products the same MAX + 1 productID (I tested it with removing ProductID as a Primary Key) I even tried this with the same result:
INSERT INTO `products2`( `ProductName`, `ProductID`, `SupplierID`, `CategoryID`, `QuantityPerUnit`, `UnitPrice`, `UnitsInStock`, `UnitsOnOrder`, `ReorderLevel`, `Discontinued`)
SELECT CONCAT(p.ProductName, '_V2'), (SELECT x.ProductID FROM (SELECT p.ProductID, ROW_NUMBER() OVER( ORDER BY ProductID DESC) AS rank FROM products2 p) AS x WHERE x.rank = 1) +1, p.SupplierID,p.CategoryID, 30, p.UnitPrice * 2, 10, 20, 2, 'n'
FROM products2 p
WHERE p.Discontinued = 'y';
I can’t get the Subquery to be re-run per Insert
2
Answers
You can tweak your query to assign the
max(ProductID)
in a subquery to a variable and then increment your variable within your query.Here is a simplified way that you can use on your problem:
See it working here
With MySQL 8 CTE and ROW_NUMBER was introduced, so use thm like
fiddle