MySQL incrementing value

后端 未结 5 1521
情话喂你
情话喂你 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 15:58

    You will need to ORDER BY id_category and use two user variables so you can track the previous category id -

    SET @position := 0;
    SET @prev_cat := 0;
    
    INSERT INTO products
    SELECT id_product, id_category, name, position
    FROM (
        SELECT
            id_product,
            id_category,
            name,
            IF(@prev_cat = id_category, @position := @position + 1, @position := 1) AS position,
            @prev_cat := id_category
        FROM db2.products
        ORDER BY id_category ASC, id_product ASC
    ) AS tmp;
    

    This will allow you to do all categories in one query instead of category by category.

提交回复
热议问题