-1

我有 2 个简单的选择查询来获取我的 id 列表。我的第一个表返回让我们说 5 个 ID。1、2、5、10、23

我的第二个表返回 50 个 id 的列表,没有任何顺序。

编写查询以将第一个表中的每个 id 映射到第二个表中的所有 id 的最有效方法是什么?

编辑:对不起这里有更多信息。

如果表 1 的结果为 ids = 1、2、5、10、23,而表 2 的结果为 ids = 123、234、345、456、567

我想写一个插入表 3 这些值

 Table1ID | Table2ID
         1|123 
         1|234
         1|345
         1|456
         1|567
         2|123 
         2|234
         2|345
         2|456
         2|567

等等。

4

2 回答 2

0

It seems like what you are looking for is a Cartesian Product.

You can accomplish this simply by joining the two tables together with no join condition, which is accomplished by CROSS JOIN.

INSERT dbo.TableC (AID, BID)
SELECT A.ID, B.ID
FROM
   dbo.TableA A
   CROSS JOIN dbo.TableB B
;

Here is an image with a visualization of a Cartesian product. The inputs are small, just the column of symbols on the left corresponding to the first table, and the column on the right being the second table. Upon performing a JOIN with no conditions, you get one row per connecting line in the middle.

Cartesian Product

于 2013-04-05T22:32:03.747 回答
0

使用INSERT INTO ... SELECT带有交叉连接的语句:

INSERT INTO TableC (ID1, ID2)
SELECT A.ID AS ID1, b.ID AS ID2 FROM TableA A CROSS JOIN TableB B;

示例演示

INSERT INTO…SELECT在 MSDN 上有描述:INSERT (Transact-SQL)

您可以使用INSERT INTO <target_table> SELECT <columns> FROM <source_table>有效地将大量行从一个表(例如临时表)传输到另一个具有最少日志记录的表。最少的日志记录可以提高语句的性能并减少操作在事务期间填满可用事务日志空间的可能性。

于 2013-04-05T21:49:11.053 回答