MySQL - 在插入期间指定一个列值,其结果为select

时间:2017-10-09 20:17:01

标签: mysql

我正在使用MySql 5.7,并且有一个类似于这样的用户表:

create table user (
   id          int unsigned   not null auto_increment primary key ,
   first_name  varchar(30)    not null                            ,
   last_name   varchar(30)    not null                            ,
   user_name   varchar(15)    not null unique                     ,
   email       varchar(100)   not null                            ,
   phone       varchar(255)       null                            ,
   address     varchar(100)       null                            ,
   created_by  int unsigned   not null                            ,
   created_on  timestamp      not null                            ,
   modified_on timestamp          null                           );

我在表格中插入一行,以便创建一种" admin"用户申请。

insert into user value (0, "plm", "admin", "plm_admin",  "do_not_replay@my_company.com", "111-222-3333", null, 1, now(), null);

然后我想在用户表中插入更多用户。但是当这样做时,我想指定" created_by" field被设置为" system"的id。我刚创建的用户" plm_admin"。

以下是我尝试做的一个例子:

insert into user value (0, "steve", "smith", "ssmith" , "steve.smith@my_company.com", "111-222-4444", null, select id from user where user_name = "plm_admin", now(), null);

这个sql不起作用,但希望你明白在插入用户史蒂夫史密斯的值时,我想为用户指定id" plm_admin"作为" created_by"的值列。

1 个答案:

答案 0 :(得分:0)

这个怎么样?

此外,您的插入内容有一列太多 - " Active"似乎没有一个专栏可以用它

insert into user value (0, "plm", "admin", "plm_admin", "do_not_replay@my_company.com", "111-222-3333", null, 1, now(), null);
SET @id = LAST_INSERT_ID();
insert into user value (1, "steve", "smith", "ssmith" , "steve.smith@my_company.com", "111-222-4444", null, @id, now(), null);
insert into user value (2, "john", "smith", "jsmith" , "john.smith@my_company.com", "111-222-4444", null, @id, now(), null);