I came up with the following trick in response to a question in
the #mysql channel on Freenode. A user needed to create a unique
identifier for multiple otherwise duplicate entries. Yes that was
bad schema design to begin with, but it was a fun challenge to
see if it could be resolved without scripting. And it can... it's
based on a known trick of numbering output rows. What's new is
restarting the counter for each group (name).
CREATE TABLE number (name CHAR(10), val INT DEFAULT 0);
INSERT INTO number (name)
VALUES ('foo'),('bar'),('foo'),('foo'),('bar');
SET @lastval=0, @lastuser='';
UPDATE number
SET val=(@lastval:=IF(name=@lastuser,@lastval+1,1)),
name=(@lastuser:=name)
ORDER BY name;
SELECT * FROM number ORDER BY name,val;
+------+------+
| name | val |
+------+------+
| bar | 1 |
| bar | 2 |
| foo | 1 |
| foo | 2 |
| foo | 3 |
+------+------+