mysql increment value based on previous record

守給你的承諾、 提交于 2019-12-11 02:33:24

问题


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.



来源:https://stackoverflow.com/questions/45616065/mysql-increment-value-based-on-previous-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!