一个查询可从不同表中获取多个不相关的列

时间:2018-12-07 06:55:47

标签: mysql

说我有3个表:table1,table2和table3。我本质上想将以下3个查询组合在一起:

  1. SELECT columnA FROM table1
  2. SELECT columnB FROM table2
  3. SELECT columnC FROM table3

列的大小可能不同,我想避免重复数据。因此,如果columnA具有3个元素,columnB具有1个元素,columnC具有2个元素,我将得到一个表格,其中每个列具有相应数量的元素。未填充的行可以保留为NULL。

如何创建一个完成此任务的查询?

简单的查询SELECT DISTINCT table1.columnA, table2.columnB, table3.columnC FROM table1, table2, table3只是给了我一张这些列中所有元素的所有可能组合的表。

4 个答案:

答案 0 :(得分:1)

UNION ALLUNION可以帮助您。取决于您是否要重复:

SELECT columnA FROM table1
UNION ALL
SELECT columnB FROM table2
UNION ALL
SELECT columnC FROM table3

有关更多信息,请阅读:https://dev.mysql.com/doc/refman/8.0/en/union.html

编辑:

您可以在第二列中使用修正文本来区分应用程序中的记录:

SELECT columnA,'TABLE1' FROM table1
UNION ALL
SELECT columnB,'TABLE2' FROM table2
UNION ALL
SELECT columnC,'TABLE3' FROM table3

答案 1 :(得分:1)

如果仅需要不同的值,则可以使用UNION

SELECT columnA , 'T1' t_name
FROM table1
UNION
SELECT columnB, 'T2'  
FROM table2
UNION
SELECT columnC , 'T3' 
FROM table3

但如果需要所有值,则应使用UNION ALL

SELECT columnA, 'T1' t_name
FROM table1
UNION ALL
SELECT columnB, 'T2' 
FROM table2
UNION ALL
SELECT columnC , 'T3' 
FROM table3

答案 2 :(得分:1)

如果采用联合思想并添加行号,则可以创建一个行号列表,然后将其用于左联接三个表。例如

drop table if exists t1,t2,t3;
create table t1(id int);
create table t2(id int);
create table t3(id int);

insert into t1 values(1),(3);
insert into t2 values(10),(20),(40);
insert into t3 values(3);


select s.rownumber,t1.id t1id
        ,t2.id t2id
        ,t3.id t3id
from
(
select @r1:=@r1+1 rownumber from t1 cross join(select @r1:=0) r1
union 
select @r2:=@r2+1 rownumber from t2 cross join(select @r2:=0) r2
union 
select @r2:=@r3+1 rownumber from t3 cross join(select @r3:=0) r3
) s
left join (
select id,@r4:=@r4+1 rownumber from t1 cross join(select @r4:=0) r4
) t1 on t1.rownumber = s.rownumber
left join (
select id,@r5:=@r5+1 rownumber from t2 cross join(select @r5:=0) r5
) t2 on t2.rownumber = s.rownumber
left join (
select id,@r6:=@r6+1 rownumber from t3 cross join(select @r6:=0) r6
) t3 on t3.rownumber = s.rownumber
;

+-----------+------+------+------+
| rownumber | t1id | t2id | t3id |
+-----------+------+------+------+
|         1 |    1 |   10 |    3 |
|         2 |    3 |   20 | NULL |
|         3 | NULL |   40 | NULL |
+-----------+------+------+------+
3 rows in set (0.00 sec)

答案 3 :(得分:0)

您可以尝试使用联合

    SELECT columnA FROM table1
    union
    SELECT columnB FROM table2
    union 
    SELECT columnC FROM table3