问题
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