I have a (MYSQL) table in the following format; assuming the name of the table ismytable
:
id | Name | Group |
---|---|---|
123 | Name 1 | 1 |
124 | Name 2 | 2 |
125 | Name 3 | 1 |
126 | Name 4 |
id
is unique and auto-incrementing.name
is a unique string,group
is just an integer
I now want to assignname4
to a newgroup
that does not exist yet, so thegroup
ofname4
in this example cannot It's1
or2
.
For example, the result might be:
id | Name | Group |
---|---|---|
126 | Name 4 | 3 |
Currently I'm sorting bygroup
descending and just manually inserting the maximum number 1, but I'd like to know if there's a better/faster way to generate new unique values in the column.group
has no constraints other than being an integer.
I'm using MySQL Workbench, so I can use SQL commands as well as Workbench-specific options if available.
If anything is unclear, I'll be happy to provide clarification.
In MySQL 8.0, you can get help on two window functions:
MAX
, retrieve the maximum "group" valueROW_NUMBER
, retrieves the incremental value for each NULL present in the table.You can then sum these two values and update the table with the "Group" field being empty.
See the demohere.
In MySQL 5.X, you can use a variable, initialize it with the largest "group" value, and then update it incrementally in a
UPDATE
statement. >SET clause.See the demohere.