简体   繁体   English

将数据插入到数据来自两个 SELECT 查询的表中

[英]Insert data into table where data comes from two SELECT queries

I have a table that I need to insert data to.我有一个需要向其中插入数据的表。 The table has 2 columns:该表有 2 列:

ClassStudents (table)班级学生(表)

  • ClassId班级号
  • StudentId学生卡

The data I want to insert can be found from 2 tables:我要插入的数据可以从 2 个表中找到:

Classes (table)类(表)

Students (table)学生(表)

I need to get relevant Classes.Id and relevant Students.Id and insert them to ClassStudents table.我需要获取相关的 Classes.Id 和相关的 Students.Id 并将它们插入 ClassStudents 表。 I can get the relevant data from each table but I don't know how to insert those data to ClassStudents.我可以从每个表中获取相关数据,但我不知道如何将这些数据插入到 ClassStudents。 The data of the 2 tables won't have the same number of records: Classes will have fewer records than Students, but I need to insert a combination of all Classes.Id to Students.Id and insert to ClassStudents table all those combinations. 2 个表的数据不会有相同数量的记录:类的记录数将少于学生,但我需要将所有 Classes.Id 的组合插入到 Students.Id 并将所有这些组合插入 ClassStudents 表。

I am thinking I need a CROSS JOIN and then use that to insert but I don't know how to or if its even allowed to CROSS JOIN two select queries (one from Classes to get all relevant data and one from Students for also, relevant data).我在想我需要一个 CROSS JOIN 然后用它来插入,但我不知道如何或者它是否甚至允许 CROSS JOIN 两个 select 查询(一个来自 Classes 以获取所有相关数据,一个来自 Student 也,相关数据)。

You don't provide any requisit sample data and the result expected.您不提供任何必要的样本数据和预期的结果。

However you probably (and if not you'll need to clarify) just need a union但是,您可能(如果不是,则需要澄清)只需要一个工会

Insert into ClassStudents (ClassId, StudentId)
select ClassId, StudentId
from Classes
union
select ClassId, StudentId
from Students

If you need to keep duplicates, use union all .如果您需要保留重复项,请使用union all

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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