How to join two unrelated tables in sql

落爺英雄遲暮 提交于 2019-11-30 00:44:59

问题


I have two tables:

Table 1: Formulas

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

Table 2: Context

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, i.e.

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]

回答1:


You can use the Cartesian Product of the two tables as follows:

SELECT * FROM Formulas, Context

This would result in M * N rows.




回答2:


You want to use a CROSS JOIN:

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



回答3:


Did you try CROSS APPLY:

select *
from context
cross apply formulas
order by contextid

See SQL Fiddle With Demo




回答4:


You can only do Cross Join. Other joins can be done only with related tables.



来源:https://stackoverflow.com/questions/12719266/how-to-join-two-unrelated-tables-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!