mysql - 高级sql查询

标签 mysql sql database oracle postgresql

我必须在我的数据库中创建表:

table1
column1|column2|column5|column13
harry   marry   stan    kyle

table2
column1|column2|column12|column7
kenny   eric    randy    ike

如您所见,每个表中有两列名称相同,两列名称不同,我想将它们合二为一,这是我想要实现的输出

column1|column2|column5|column13|column12|column7
harry   marry   stan    kyle     null     null
kenny   eric    null    null     randy    ike

column1|column2|column5|column12|column13|column7
harry   marry   stan    null     kyle     null
kenny   eric    null    randy    null     ike

这可能吗?如何?我试过类似的东西:

(select t1.column1 from table1 t1 union select t2.column1 from table t2)

但是我卡住了..

最佳答案

你应该可以做到

SELECT t1.column1, 
       t1.column2, 
       t1.column5, 
       null column12, 
       t1.column13, 
       null column7
  FROM table1 t1
UNION ALL
SELECT t2.column1, 
       t2.column2, 
       null column5, 
       t2.column12, 
       null column13, 
       t2.column7
  FROM table2 t2

如果数据类型(特别是长度)很重要,您可能希望CAST(null as VARCHAR2(100)) 而不是在第一个查询中只选择 NULL。

关于mysql - 高级sql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5966146/

相关文章:

MySQL 不一致地更改与 InnoDB 表上的外键关联的索引名称

mysql - 按 X 或 Y 分组?

php - 拉拉维尔。如果数据库正在播种,则禁用观察者方法

MySQL 错误代码 1215 : “Cannot add foreign key constraint”

php - 通过 Azure MySQL 检查用户的登录

php - 使用 php 在文本字符串中创建 url

c# - 从源代码在 sql 查询中传递 Request.QueryString 整数值

mysql - 子查询还是 INNER JOIN?

sql-server - asp.net + MS SQL Server : Best Source Control

mysql - mongo 是否适合与 MySQL 一起使用?