mysql 行自动增量为23,非主键上的mysql自动增量

Another question today :)

This time I'd like to know if/how it's possible to make a second column auto-increment for each primary key:

CREATE TABLE test (

`id` INTEGER UNSIGNED NOT NULL,

`subId` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,

`text` VARCHAR(45) NOT NULL,

PRIMARY KEY (`id`, `subId`)

)

ENGINE = InnoDB;

This creation, unfortunately, doesn't work, only if I specify ID as primary key and subId as index key (but I need them both together and ID can repeat...)

Example data (what I need):

1, 1

1, 2

1, 3

2, 1

2, 2

3, 1

The problem with making ID primary and subId index is that subId will increment independently of ID.

How to achieve this and is it even possible?

解决方案

I had to deal with a similar problem ordering a category tree unnaturally.

If you are inserting all the rows for one id at one time, you could do something like this for each subId:

SET @seq = 0;

INSERT INTO test

(id, subId, text) VALUES

(_id, @seq := @seq + 1, 'Some text')

;

If you need to "add" a row to an id, you can set @seq with

SELECT IFNULL(MAX(subId), 0) INTO @seq FROM test WHERE id = _id;

This would of course require management of id by the application and not mySQL.

You could do that same as the last code block to get the next available id as well.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值