2015-11-02 78 views
0

我想编写一个sql脚本,该脚本将一些其他表中的所有id插入到表中。将值插入到另一个表中的所有行的一个表中

create table person 
(
    id int(11) not null auto_increment, 
    name varchar(255), 
    primary key (id) 
); 

insert into person 
values (null, 'John'), (null, 'Sam'); 

select * from person; 

id | name 
---------- 
1 | John 
2 | Sam 

create table phone_details 
(
    id int(11) not null auto_increment, 
    person_id int(11), 
    phone int(11), 
    constraint person_ibfk_1 foreign key (person_id) references person (id) on delete no action, 
    primary key (id) 
); 

现在,在phone_details表,我想以下几点:

id | person_id | phone 
---------------------------- 
1 | 1  | 9999999999 
2 | 2  | 9999999999 

我该怎么办呢?目前,我正在使用Java来编写这个一次性脚本,但我认为在sql中必须有这样做的方法。

回答

3

您可以使用INSERT INTO ... SELECT语法:

INSERT INTO phone_details(person_id,phone) 
SELECT id, 99999999 
FROM person; 

考虑storing phone numberVARCHAR

SqlFiddleDemo

+0

我得到的错误与上面的查询:SQL错误[1054] [42S22]: 'PERSON_ID' 未知列在 '字段列表' – OneMoreError

+0

@OneMoreError查看更新后 – lad2025

+1

是啊。这工作。谢谢。 – OneMoreError

相关问题