Create new unique value in column
P粉210405394
P粉210405394 2023-09-16 13:14:40
0
1
733

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.

P粉210405394
P粉210405394

reply all (1)
P粉205475538

In MySQL 8.0, you can get help on two window functions:

  • MAX, retrieve the maximum "group" value
  • ROW_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.

WITH cte AS ( SELECT id, name, MAX(group_) OVER() + ROW_NUMBER() OVER(PARTITION BY group_ IS NULL ORDER BY name) AS new_group FROM tab ) UPDATE tab INNER JOIN cte ON tab.id = cte.id AND tab.name = cte.name SET tab.group_ = cte.new_group WHERE tab.group_ IS NULL;

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 aUPDATEstatement. >SET clause.

SET @maxgroup = NULL; SELECT MAX(group_) INTO @maxgroup FROM tab; UPDATE tab SET group_ = (@maxgroup:= @maxgroup + 1) WHERE group_ IS NULL; ORDER BY id;

See the demohere.

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!