简体   繁体   English

MySQL-2个具有不同列的表的并集

[英]Mysql - union of 2 tables with different columns

I know the topic is already on other threads, but my problem is that i could not use union (table 1 has 60 columns; table 2 has only 7). 我知道该主题已经在其他线程上,但是我的问题是我无法使用联合(表1有60列;表2只有7列)。 Is there another way than creating for table 2 ...53 empty columns? 除了为表2 ... 53创建空列之外,还有其他方法吗?

Is it possible to generate the result in one query? 是否可以在一个查询中生成结果?

Thank you! 谢谢!

You can simply do this by replacing non existent columns with nulls like below 您可以通过将不存在的列替换为空来简单地做到这一点,如下所示

Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2

Replace the columns in tables with null if the column does not exist. 如果列不存在,请将表中的列替换为null。

It is possible, since you can add any number of arbitrary columns in a select: 这是可能的,因为您可以在选择中添加任意数量的任意列:

select field1, field2, field3 from table1
union
select field4, null, field5 from table2

In the above example I used a constant null value as the 2nd field, but you can choise any value befitting the data type of the existing column in the other table. 在上面的示例中,我使用了一个恒定的空值作为第二个字段,但是您可以选择适合另一个表中现有列的数据类型的任何值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM