我有一个包含以下表结构的表代码。 id是自动递增id,代码是随机唯一的15位数代码,customer_id是客户的id。该表有近13万行
id code customer_id
1 123...4 1
2 124...5 1
3 128...3 1
4 234...1 2
5 678...3 2
6 567...8 1
我在表中添加了一个列serial_number,我想添加一个serial_number,它将根据现有值的customer_id为下面各个客户的每个值递增。我如何在mysql中执行此操作?
id code customer_id serial_number
1 123...4 1 1
2 124...5 1 2
3 128...3 1 3
4 234...1 2 1
5 678...3 2 2
6 567...8 1 4
我试过这种方法,但我的mysql连接正在超时:
MySQL: Add sequence column based on another field
CREATE temporary table serial_number ( id bigint, serial_number int);
INSERT INTO serial_number ( id, serial_number )
SELECT id,
(SELECT count(*) + 1 FROM code c
WHERE c.id < code.id AND c.customer_id = code.customer_id) as serial_number
FROM code;
UPDATE test INNER join serial_number ON code.id = serial_number.id SET code.serial_number = serial_number.serial_number;
错误代码:2013。查询期间与MySQL服务器的连接丢失