简体   繁体   English

SQL查询从表A中获取表B中每个ID的所有ID,然后插入表C中?

[英]SQL query to grab all id's from Table A for each id in Table B and insert into Table C?

I'm trying to come up with a SQL query that I could easily do in code but is really foreign to me in SQL. 我正在尝试提出一个SQL查询,我可以很容易地在代码中进行查询,但是对SQL来说确实是陌生的。

Since I want to be as generic as possible, I wrote out the psuedocode: 因为我想尽可能通用,所以我写出了psuedocode:

foreach (record in TableA)
     foreach (record in TableB)
        var newRecord = new record(TableA.id, TableB.id)
        TableC.Add(newRecord) // TableC.id is autoincremented  
     end foreach
end foreach

Would I use a WHILE loop or is there a better way to accomplish this? 我将使用WHILE循环还是有更好的方法来完成此操作? I am using SQL Server 2008. Thanks. 我正在使用SQL Server2008。谢谢。

You want to think in terms of sets. 您想从集合的角度思考。 The operation you are looking for is a cross join . 您要查找的操作是cross join This produces every combination from the two tables (a cartesian product): 这将产生两个表的所有组合(笛卡尔乘积):

select a.id, b.id
from A cross join B

To insert this into a table, you can then use an insert : 要将其插入到表中,可以使用insert

insert into c(aid, bid)
    select a.id, b.id
    from A cross join B

Maybe this: 也许这样:

INSERT INTO TableC (ColumnA, ColumnB, ...)
SELECT A.something, B.somethingElse
FROM TableA A
INNER JOIN TableB B ON A.someKey = B.anotherKey
WHERE something = aValue

暂无
暂无

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

相关问题 根据列从表B中进行SQL SELECT,但根据表A ID捕获所有行 - SQL SELECT from TABLE B based on column but grab all rows based on TABLE A ID 表中每个 ID 的 SQL 查询 - SQL query for each ID in table SQL:查找表的“A”ID 是否存在于表的“B”ID - SQL : Find if table's 'A' ID exists to table's 'B' ID 从一个表中获取最后一个插入ID,然后放入另一个表中 - Grab the last insert id from one table to put into another table SQL 查询来自两个表和一个链接表,以返回表 c 的所有表 a 的每一行,其中表 b 中没有链接 - SQL query from Two tables and a link table to return all of table c for each row of table a with nulls where the is no link in table b SQL C++/CLi - 知道某物是否在表中的方法,如果是,则使用它的 id,如果没有,则生成新的 id 并抓取它 - SQL C++/CLi - Way to know if something is in a table if yes use it's id, if not generate the new id and grab it SQL Server:将行插入表中,对于所有 id 尚不存在 - SQL Server: Insert row into table, for all id's not existing yet SQL基于表C从表B插入表A中 - SQL Insert into table A from table B based off table C 从A表插入数据到B表,然后用B表ID更新A表 - Insert data from Table A to Table B, then Update Table A with Table B ID 如何从表 A 中获取 select,然后通过一个查询在表 B 中插入选定的 ID? - How to select from table A and then insert selected id inside table B with one query?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM