两个SELECT语句之间的MySQL笛卡尔积

时间:2010-12-19 03:03:27

标签: mysql select join

我想在两个SELECT语句之间执行笛卡尔积,如

SELECT 1, 2     INNER JOIN     SELECT 3, 4 ;

我希望结果是(1,2)和(3,4)的每个组合,如:

1  3
2  3
1  4
2  4

5 个答案:

答案 0 :(得分:12)

如果您在JOIN ON子句中指定了没有任何WHERE子句或等式/条件的表,您将获得您正在寻找的catesian产品。

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

会给你你所要求的东西。更明确地展示......

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 |
+--------+--------+

答案 1 :(得分:10)

您可以使用CROSS JOIN子句

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

其中MyTable1有两行,包含1和2;和MyTable2有两行,包含3和4。

答案 2 :(得分:1)

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

甚至更简单:

select *
from
  (select 1 union
   select 2) t1,
  (select 3 union
   select 4) t2

答案 3 :(得分:0)

使用此格式时,您的格式并不像您所说的那样 A(1,2) and B(3,4) 那么交叉连接会像这样执行:

SELECT Table1.Col1, Table2.Col2
FROM Table1
CROSS JOIN Table2

(A*B)= (1,3),(1,4),(2,3),(2,4)

答案 4 :(得分:0)

mysql> select * from
    ->   (select 1 x union select 2 union select 3 union select 4) t
    ->   join
    ->   (select 1 y union select 2 union select 3) tt;
+---+---+
| x | y |
+---+---+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 2 |
| 2 | 3 |
| 3 | 1 |
| 3 | 2 |
| 3 | 3 |
| 4 | 1 |
| 4 | 2 |
| 4 | 3 |
+---+---+
12 rows in set (0.00 sec)

删除单词join可获得完全相同的结果。

select * from
  (select 1 x union select 2 union select 3 union select 4) t,
  (select 1 y union select 2 union select 3) tt;