tags:

views:

37

answers:

3

Refresh my memory. I can't recall how to join tuples (a,b) and (c) to produce (a,b)*(c). For example:

n
---
0
1
2

And

site_id     value
----------- -------------
1           a
1           b
2           c

I'd like to end up with:

site_id     value          n
----------- -------------- -- 
1           a              0
1           a              1
1           a              2 
1           b              0
1           b              1
1           b              2
2           c              0
2           c              1
2           c              2

How can I achieve this?

+2  A: 

That's called a CROSS JOIN, also known as the Cartesian product.

SELECT *
FROM Table1
CROSS JOIN Table2

You can also do it without the JOIN keyword just by using a comma:

SELECT * FROM Table1, Table2

Here's full test code you can use to verify that it works:

CREATE TABLE Table1 (n int NOT NULL);
INSERT INTO Table1 (n) VALUES
(0),
(1),
(2);

CREATE TABLE Table2 (site_id int NOT NULL, value nvarchar(100) NOT NULL);
INSERT INTO Table2 (site_id, value) VALUES
(1, 'a'),
(1, 'b'),
(2, 'c');

SELECT Table2.site_id, Table2.value, Table1.n FROM Table1, Table2

Results:

site_id  value  n
      1      a  0
      1      a  1
      1      a  2
      1      b  0
      1      b  1
      1      b  2
      2      c  0
      2      c  1
      2      c  2
Mark Byers
I tried this but it gave me every possible combination. For example (2,a,1) was contained in the results. I want ((a,b),c).
hypoxide
I must have done something wrong. This works.
hypoxide
OK. I posted some test code, but I guess you don't need it now. Never mind!
Mark Byers
+1 for the effort! Thanks Mark.
hypoxide
I'd never use the "comma" notation here for clarity, and since SQL Server 2005 in compatibility mode 90 this syntax is deprecated for outer joins anyways and the explicit JOIN syntax is always preferred! http://msdn.microsoft.com/en-us/library/ms191517.aspx
Lucero
+1  A: 

Do a CROSS JOIN

SQLMenace
+1  A: 

You can try

Select *
FROM table1, table2
astander