插入表中,选择max(column_name)+1 [英] insert into table select max(column_name)+1

查看:77
本文介绍了插入表中,选择max(column_name)+1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下构建的mysql表:

I have this mysql table built like this:

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.

A unique post_id is generated for each unique user.

我需要gen_id列为1 2 3 4 5 6等.执行插入操作时如何增加此列.我尝试了以下方法,但无法正常工作.什么是正确的方法?

I need the gen_id column to be 1 2 3 4 5 6 etc. How can I increment this column when I do an insert. I tried the one below, but it won't work. What's the right way to do this?

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.

推荐答案

尝试一下:

  INSERT INTO posts (post_user_id,gen_id) 
  SELECT 1, MAX(gen_id)+1 FROM posts;

这篇关于插入表中,选择max(column_name)+1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆