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 |
idis unique and auto-incrementing.nameis a unique string,groupis just an integer
I now want to assignname4to a newgroupthat does not exist yet, so thegroupofname4in this example cannot It's1or2.
For example, the result might be:
| id | Name | Group |
|---|---|---|
| 126 | Name 4 | 3 |
Currently I'm sorting bygroupdescending 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.grouphas 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
UPDATEstatement. >SET clause.See the demohere.