mysql increment value based on previous record

2019-07-15 01:10发布

问题:

I have a table

Id|Parent|Counter
--|------|-------
 1| A    | NULL
 2| A    | NULL 
 3| A    | NULL
 4| B    | NULL
 5| B    | NULL
 6| C    | NULL
 7| D    | NULL
 8| D    | NULL

I want to update the table such that the counter column is update (+1) as long as previous parent = parent. If not, counter =1 so:

Id|Parent|Counter
--|------|-------
 1| A    | 1
 2| A    | 2
 3| A    | 3
 4| B    | 1
 5| B    | 2
 6| C    | 1
 7| D    | 1
 8| D    | 2

I have about 3.5M records.

I can get a select query but can get it to work with update. This is what I have:

SELECT  t.Parent, (
  SELECT COUNT( * ) 
  FROM bomitems AS x
  WHERE x.id <= t.id
  AND x.Parent = t.Parent
  ) AS Counter
FROM bomitems AS t

回答1:

You wrote a good and clever query to generate those row numbers, one which avoids a messy solution using session variables. To do the update, just join your table bomitems to this query:

UPDATE bomitems t1
INNER JOIN
(
    SELECT
    t.ID,
    t.Parent,
    (SELECT COUNT(*) FROM bomitems AS x WHERE x.id <= t.id AND x.Parent = t.Parent) AS Counter
    FROM bomitems t
) t2
    ON t1.ID = t2.ID
SET t1.Counter = t2.Counter;

I tested this query on my local MySQL Workbench and it appears to be working.