2015-11-02 86 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

相關問題