MySQL incrementing value

后端 未结 5 1515
情话喂你
情话喂你 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.

    0 讨论(0)
  • 2020-12-14 15:59

    Try setting a value using a subquery like this

     (SELECT MAX(position) FROM products AS T2)+1
    

    Or

    (SELECT MAX(position) FROM products AS T2 WHERE id_category = 'product category')+1
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-12-14 16:09

    Hope this will work.

    update <tbl_name> set <column_name>=<column_name>+1 where <unique_column/s>='1'";
    
    0 讨论(0)
  • 2020-12-14 16:14

    Purely to add to @Bohemians answer - I wanted the counter to reset every so often and this can be done like such:

    SELECT *,(@position := IF (@position >= 15,1,@position + 1))

    Where 15 is obviously the maximum number before reset.

    0 讨论(0)
提交回复
热议问题