MySQL所有可能的组合形成多个表

时间:2016-05-31 06:02:23

标签: mysql database join combinations

我有三张桌子,如何获得所有可用的ID组合?

SELECT t1.id, t2.id, t3.id
FROM t1, t2, t3
WHERE 1

这个查询几乎给了我想要的东西,但也需要得到如下行:

-------------------------
| t1.id | t2.id | t3.id |
-------------------------
|   1   |  NULL | NULL  |
-------------------------
|   1   |   1   | NULL  |
-------------------------
|  NULL |   1   | NULL  |
-------------------------
|  NULL |  NULL |   1   |
-------------------------
 .......................
-------------------------

我的查询只提供没有NULL行

1 个答案:

答案 0 :(得分:1)

create table t1(id int);
create table t2(id int);
create table t3(id int);
insert into t1 values(1);
insert into t2 values(1);
insert into t3 values(1);
select * from 
(select NULL union select id from t1) x1,
(select NULL union select id from t2) x2,
(select NULL union select id from t3) x3

动态添加NULL