简体   繁体   English

如何在sql中连接两个不相关的表

[英]How to join two unrelated tables in sql

I have two tables:我有两个表:

Table 1: Formulas表 1:公式

FormulaId    Formula Text
1            [Qty] * [Rect]
2            [Qty] * [Al]
3            [Mt] * [Cat]  

Table 2: Context表 2:上下文

ContextId    Name
1            Test 1
2            Test 2
3            Test 3
4            Test 4    

I need to join those somehow in sql server 2008 R2 to get a table where for each context id I will have a full list of formulas, ie我需要以某种方式在 sql server 2008 R2 中加入那些以获得一个表格,其中对于每个上下文 id 我将有一个完整的公式列表,即

Result结果

ContextId    Name     FormulaId    Formula Text    
1            Test 1   1            [Qty] * [Rect]
1            Test 1   2            [Qty] * [Al]
1            Test 1   3            [Mt] * [Cat]
2            Test 2   1            [Qty] * [Rect]
2            Test 2   2            [Qty] * [Al]
2            Test 2   3            [Mt] * [Cat]
3            Test 3   1            [Qty] * [Rect]
3            Test 3   2            [Qty] * [Al]
3            Test 3   3            [Mt] * [Cat]
4            Test 4   1            [Qty] * [Rect]
4            Test 4   2            [Qty] * [Al]
4            Test 4   3            [Mt] * [Cat]

You can use the Cartesian Product of the two tables as follows:您可以按如下方式使用两个表的Cartesian Product

SELECT * FROM Formulas, Context

This would result in M * N rows.这将导致M * N行。

You want to use a CROSS JOIN :您想使用CROSS JOIN

SELECT FormulaId, Formula, ContextId, [Name]
FROM Formula
CROSS JOIN Context

Did you try CROSS APPLY :您是否尝试过CROSS APPLY

select *
from context
cross apply formulas
order by contextid

See SQL Fiddle With Demo参见SQL Fiddle with Demo

You can only do Cross Join.您只能进行交叉连接。 Other joins can be done only with related tables.其他联接只能对相关表进行。

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

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