合并具有不同字段名称的2个表

时间:2015-07-30 07:31:34

标签: mysql

选择*来自' BatchA'

  Table 'BatchA'

  +--------+--------+--------+
  |Fruits  | color  |  class | 
  +--------+--------+--------+
  |        |        |        | 
  |Apple   |  Red   |    x   | 
  |Apple   | Yellow |    x   | 
  |Guava   | Green  |    o   | 
  +--------+--------+--------+

选择*来自' BatchB'  表' BatchB'

  +--------+--------+--------+
  |FruitsB |  size  |  type  | 
  +--------+--------+--------+
  |        |        |        | 
  |  Apple |  Large |    A   | 
  |  Guava | Medium |    B   | 
  |  Guava |  Small |    C   | 
  +--------+--------+--------+

是否可以使用这些结果使用join或union进行查询?

结果

  +--------+--------+--------+--------+--------+--------+
  |Fruits  |  color |  class |Animals |  size  |  type  | 
  +--------+--------+--------+--------+--------+--------+
  |        |        |        |        |        |        |  
  |  Apple |  Red   |    x   |        |        |        | 
  |  Apple | Yellow |    x   |        |        |        |    
  |        |        |        |  Apple |  Large |    A   |  
  |  Guava | Green  |    o   |        |        |        |
  |        |        |        |  Guava | Medium |    B   | 
  |        |        |        |  Guava |  Small |    C   | 
  +--------+--------+--------+--------+--------+--------+

2 个答案:

答案 0 :(得分:0)

当然,您可以使用UNION

SELECT BatchA.*,null Animals,null size,null type FROM BatchA
UNION ALL
SELECT null,null,null,BatchB.* from BatchB;

这将列出两个表中NULL的所有行到那些未填充的字段。

这是假设表之间没有关系。

答案 1 :(得分:0)

MYSQL中不存在

FULL OUTER JOIN,尝试使用以下解决方法模仿其他DBMS(如ORACLE)中可用的此功能:

在两个表之间的2个查询中使用左连接和右连接的并集(知道这些表是相关的):

SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id