如何结合两个具有不同col号的表? MySQL的

时间:2014-06-25 14:15:51

标签: mysql sql

我想运行此查询:

SELECT firstName , secondName , lastName 
   FROM
       (SELECT firstName,secondName,lastName FROM table1

        UNION

        SELECT firstName,NULL,NULL FROM table2

       )resutls

我想在第二次测试中添加两个Null列,我该怎么做?

或复制firstName两次 - >

SELECT firstName , secondName , lastName 
 FROM
   (SELECT firstName,secondName,lastName FROM table1

    UNION

    SELECT firstName,firstName,firstName FROM table2

   )resutls

我想在第二个选择中添加两个cols,因为table2只有一个col(名字),如果我只选择一个col,则union将不起作用。

2 个答案:

答案 0 :(得分:2)

您的查询应该是:

SELECT firstName , secondName , lastName 
 FROM
   (SELECT firstName,secondName,lastName FROM table1
    UNION
    SELECT firstName, NULL as secondName, NULL as lastName FROM table2
   ) resutls

使用列名称的别名将其视为第二个表的新列。

这对你有用。 :)

答案 1 :(得分:1)

试试这个

SELECT firstName , secondName , lastName 
FROM
(SELECT firstName as fistname ,secondName as secondname ,lastName as lastname FROM table1

 UNION

 SELECT firstName as firstname,firstName as  '' ,firstName as '' FROM table2

 )

这将使列的名称为null