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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4481396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:03:06  来源:igfitidea点击:

MySQL cartesian product between two SELECT statements

mysqlselectjoin

提问by bobobobo

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

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

SELECT 1, 2     INNER JOIN     SELECT 3, 4 ;

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

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

1  3
2  3
1  4
2  4

回答by Riedsio

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

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

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

回答by bobs

You can use the CROSS JOIN clause

您可以使用 CROSS JOIN 子句

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.

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

回答by Athari

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

回答by Ashish Kumar

With the using this your format is not as you are saying A(1,2) and B(3,4)then the cross joinwill perform it like this:

使用此格式,您的格式与您所说的不同, 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)

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

回答by cxwangyi

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)

Removing the word joingives exactly the same result.

删除这个词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;