Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL cartesian product between two SELECT statements

Tags:

join

select

mysql

I want to perform a cartesian product between two SELECT statements as

SELECT 1, 2     INNER JOIN     SELECT 3, 4 ;

I expect the result to be every combination of (1,2) with (3,4), like:

1  3
2  3
1  4
2  4
like image 575
bobobobo Avatar asked Dec 19 '10 03:12

bobobobo


3 Answers

If you specify your tables with out any JOIN ON clause or equalities/conditionins in the WHERE clause you'll get the catesian product you're looking for.

SELECT table1.field1, table2.field2
FROM table1, table2

will give you what you're asking for. Showing it more explicitly...

SELECT * FROM table1;
+--------+
| field1 |
+--------+
|      1 |
|      2 |
+--------+

SELECT * FROM table2;
+--------+
| field2 |
+--------+
|      3 |
|      4 |
+--------+

SELECT table1.field1, table2.field2 FROM table1, table2;
+--------+--------+
| field1 | field2 |
+--------+--------+
|      1 |      3 |
|      2 |      3 |
|      1 |      4 |
|      2 |      4 |
+--------+--------+
like image 118
Riedsio Avatar answered Oct 12 '22 00:10

Riedsio


You can use the CROSS JOIN clause

SELECT MyTable1.Col1, MyTable2.Col2
FROM MyTable1
CROSS JOIN MyTable2

where MyTable1 has two rows containing 1 and 2; and MyTable2 has two rows containing 3 and 4.

like image 41
bobs Avatar answered Oct 11 '22 23:10

bobs


select v1, v2
from
  (select 1 as v1 union
   select 2) t1,
  (select 3 as v2 union
   select 4) t2

or even simpler:

select *
from
  (select 1 union
   select 2) t1,
  (select 3 union
   select 4) t2
like image 27
Athari Avatar answered Oct 11 '22 23:10

Athari