简体   繁体   中英

Insert multiple rows from two tables into one table

I have two tables with a number of rows in each. I want to "merge" these two into another table, how would I go about and do that?

I've tried INSERT INTO SELECT , but it's not doing what I want (or maybe I'm possibly doing it wrong).

The Tables I have are:

Versions
  [version] VARCHAR(10)

Semesters
  [id] INT
  [semester] INT
  [name] VARCHAR(150)

Versions_semesters
  [semesterid] INT
  [version] VARCHAR(10)

Some example data from Versions and Semesters:

Versions
  'Version1.0'
  'Version1.5'

Semesters
  1, 15, 'Autumn15'
  2, 15, 'Spring15'
  3, 15, 'Fall15'
  4, 16, 'Autumn16'
  5, 16, 'Spring16'
  6, 16, 'Fall16'

What I'd want to achieve is a table holding versions related to semesterIDs.

I can get the subsets I want by doing the following:

SELECT id FROM semesters WHERE semester = 16;
SELECT * from Versions;

And these two subsets I'd like to INSERT INTO Versions_semesters so it looks like this:

Versions_semesters
  4, 'Version1.0'
  5, 'Version1.0'
  6, 'Version1.0'
  4, 'Version1.5'
  5, 'Version1.5'
  6, 'Version1.5'

Anyone have an elegant (or ugly) solution to this? I guess a CROSS JOIN could be used as I have the subsets extracted, but how do I do both get the subsets and then Join them?

You are looking for a CROSS JOIN which is the Cartesian product of the two tables.

INSERT INTO Table3
(ID,Version)
SELECT Id,Version
FROM Table1 CROSS JOIN Table2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM