[英]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.