Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

sql server - SQL INSERT INTO from multiple tables

this is my table 1:

NAME       AGE        SEX        CITY             ID

Clara      22         f          New York         1
Bob        33         m          Washington       2
Sam        25         m          Boston           3

this is my table 2:

NUMBER       ID
555-1111     1
555-2222     2
555-3333     3

and now I want a table 3 which shows me all information:

NAME       AGE        SEX        CITY             ID        NUMBER

Clara      22         f          New York         1         555-1111
Bob        33         m          Washington       2         555-2222
Sam        25         m          Boston           3         555-3333

I tried first to insert into table 3 only the values from table 1 and then I inserted into table 3 the values from table 2 with an inner join where Id = Id is.

INSERT INTO table3 { name, age, sex, city, id}
SELECT name, age, sex, city, id
FROM table 1



INSERT INTO table3 { name, age, sex, city, id, number}
SELECT name, age, sex, city, id, number
FROM table 2 p
INNER JOIN table 3 c ON c.Id = p.Id

But all I get is a duplication of my values. instead of having 3 entries, I have like 9 entries, which some have number null, some have only the number and the rest null, and some are correct.

I hope someone can help me

EDIT

If I am having now a third Table like this one:

NATIONALITY       ID

Canadian          1
American          2
French            3

How could I merge all 3 tables into one Table?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You only need one INSERT:

INSERT INTO table4 ( name, age, sex, city, id, number, nationality)
SELECT name, age, sex, city, p.id, number, n.nationality
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id
INNER JOIN table3 n ON p.Id = n.Id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...