Update/Increment a single column on multiple rows at once

后端 未结 3 756
谎友^
谎友^ 2020-12-25 12:58

I\'m trying to add rows to a column, keeping the order of the newest column set to one, and all other rows counting up from there.

In this case, I add

相关标签:
3条回答
  • 2020-12-25 13:02

    What you are telling the DB to do it update EVERY record in the table by incrementing its order field by one. So EVERY record will always have the same value. I beleive you are trying to set the latest record to 1 and the oldest record set to (no records+1).

    So maybe you can try this:

    set @count = (SELECT COUNT(ID) from favorits);
    UPDATE favourits SET order = @count-ID+1
    

    Now this is assuming that no records are deleted. In that case you would have to adjust for this and set the latest record to 1 and then increment the order value for each previous record sorted by ID.

    So this would be the approach:

    set @i=0;
    set @Count=(SELECT COUNT(*) from favorits);
    
    UPDATE favorits SET `order` = @Count-(@i:=@i+1)+1;
    
    0 讨论(0)
  • 2020-12-25 13:08
    SET @a = 0;  
    UPDATE favorits SET order = @a:=@a+1;
    
    0 讨论(0)
  • 2020-12-25 13:20

    I got intereted, so I came up with the following solution. Consider the following table:

    CREATE TABLE `placements` (
      `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
      `user` varchar(12) NOT NULL,
      `place` tinyint(3) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8; 
    
    INSERT INTO `placements` (`id`, `user`, `place`) VALUES
    (1, 'Adam', 1),
    (2, 'Bill', 2),
    (3, 'Carl', 3),
    (4, 'Doug', 4),
    (5, 'Eddy', 5),
    (6, 'Frank', 6),
    (7, 'George', 7),
    (8, 'Harry', 8),
    (9, 'Ian', 9),
    (10, 'John', 10);
    

    So, lets say you have John go up against Adam for the #1 place and John wins:

    UPDATE placements 
    SET place = place +1 
    WHERE user != "John";
    
    UPDATE placements 
    SET place = 1 
    WHERE user = "John";
    

    John is now in first place, and everybody else was bumped down a position. Now lets say that George goes up against Carl for Carl's position (currently placement #4). George wins: That means George is now place #4, and Carl place #5. What happens to Georges old position of #8?

    UPDATE placements 
    SET place = place +1 
    WHERE place > 3 
    AND place < 9 
    AND user != "George";
    
    UPDATE placements 
    SET place = 4 
    WHERE user = "George";
    

    So, it's really not that hard to do. You just have to know the current placement of some of your users, and adjust your MySQL queries as needed.

    If you paste these queries into your terminal or phpMyAdmin (or whatever you use), and follow along, you'll see that it works.

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