【发布时间】:2012-11-08 03:49:13
【问题描述】:
我有这个 mysql 表是这样构建的:
CREATE TABLE `posts` (
`post_id` INT(10) NOT NULL AUTO_INCREMENT,
`post_user_id` INT(10) NOT NULL DEFAULT '0',
`gen_id` INT(10) NOT NULL DEFAULT '0',
PRIMARY KEY (`post_user_id`, `post_id`)
)
COLLATE='utf8_general_ci'
ENGINE=MyISAM;
当我这样做时:
insert into posts (post_user_id) values (1);
insert into posts (post_user_id) values (1);
insert into posts (post_user_id) values (2);
insert into posts (post_user_id) values (1);
select * from posts;
我明白了:
post_id | post_user_id | gen_id
1 1 0
2 1 0
1 2 0
3 1 0
为每个唯一用户生成一个唯一的 post_id。
我需要 gen_id 列为 1 2 3 4 5 6 等。我如何在插入时增加此列。我尝试了下面的一个,但它不起作用。这样做的正确方法是什么?
insert into posts (post_user_id,gen_id) values (1,select max(gen_id)+1 from posts);
//Select the highest gen_id and add 1 to it.
【问题讨论】:
-
post_id 为每个用户提供一个从 1 开始的 id。这就是为什么我需要一个单独的列 1 2 3 4 5 6 等。
-
我不明白。当您希望 gen_id 与 post_id 相同时,为什么还要麻烦添加该列?
-
我不希望它和 post_id 一样。用户 1 的 post_id 为 123,用户 2 的 post_id 为 12345。 gen_id = 123456789 10 11 12 。它不是从每个用户的 1 开始的。