首页 > 解决方案 > 使用最后插入的 id 作为用户名

问题描述

我希望每当我插入一行时,新生成的 id 都可以用作用户名,也可以插入到 user_name 字段中。任何关于我如何实现这一目标的想法都会非常感激。我试图在 mysql 工作台上运行下面的代码,除了插入语句之外,一切似乎都运行良好。

create database if not exists mydatabase;
create table if not exists mydatabase.mytable
(
    id int auto_increment not null,
    user_name int not null,
    pass_word varchar(100),
    primary key(id)
);
insert into mydatabase.mytable(user_name,pass_word) values (select SCOPE_IDENTITY(),'mypass');

标签: mysqlsql

解决方案


不确定您的 sql 版本是否支持多个 auto_increment 列。但是我认为您可以在每次插入时创建触发器或插入以下内容:

update my_table
set user_name = id

推荐阅读