MySQL incrementing value

后端 未结 5 1517
情话喂你
情话喂你 2020-12-14 15:20

Is there a way to make a value increment with every insert if having multiple inserts? (I dont speak of the primary key that autoincrements)

Lets say I have a struct

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 16:04

    Yes: Use a user defined variable:

    SET @position := 0; -- Define a variable
    INSERT INTO products
    SELECT id_product, id_category, name, (@position := @position + 1)
    FROM db2.products
    WHERE id_category = xxx;
    

    The result of increment to @position is the value used for the insert.


    Edit:

    You can skip the declaration of the variable by handling the initial value in-line:

    ...
    SELECT ..., (@position := ifnull(@position, 0) + 1)
    ...
    

    This can be particularly handy when executing the query using a driver that does not allow multiple commands (separated by semicolons).

提交回复
热议问题