mysql中加一列序列,MySQL:根据另一个字段添加序列列

I'm working on some legacy code/database, and need to add a field to the database which will record a sequence number related to that (foreign) id.

Example table data (current):

ID ACCOUNT some_other_stuff

1 1 ...

2 1 ...

3 1 ...

4 2 ...

5 2 ...

6 1 ...

I need to add a sequenceid column which increments separately for each account, achieving:

ID ACCOUNT SEQ some_other_stuff

1 1 1 ...

2 1 2 ...

3 1 3 ...

4 2 1 ...

5 2 2 ...

6 1 4 ...

Note that the sequence is related to account.

Is there a way I can achieve this in SQL, or do I resort to a PHP script to do the job for me?

TIA,

Kev

解决方案

This should work but is probably slow:

CREATE temporary table seq ( id int, seq int);

INSERT INTO seq ( id, seq )

SELECT id,

(SELECT count(*) + 1 FROM test c

WHERE c.id < test.id AND c.account = test.account) as seq

FROM test;

UPDATE test INNER join seq ON test.id = seq.id SET test.seq = seq.seq;

I have called the table 'test'; obviously that needs to be set correctly. You have to use a temporary table because MySQL will not let you use a subselect from the same table you are updating.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值