在新表中组合两个表

时间:2016-02-24 10:21:19

标签: mysql sql database

我的两张表是:

PkID | HouseFk | house_extra_id | Price | discount_id
1    | 5       | 6              | 1205  | 0

PkID | HouseFk | PacketFk | Price | discount_id
1    | 6       | 7        | 500   | 0

如何将这两者合并到一个新表中,该表未存储在数据库中但仅用于输出。我已经尝试了joinunion all,但我无法获得所需的表格结构。我想要第一个和第二个表的列,需要NULL值,如下所示:

PkID | HouseFk | house_extra_id | Price | discount_id | PacketFk
1    | 5       | 6              | 1205  | 0           | NULL
1    | 6       | NULL           | 500   | 0           | 7

如果我在join上使用HouseFk我只会获得两个表中都存在HouseFk值的合并行,而union all会遗漏一些列!

3 个答案:

答案 0 :(得分:3)

使用union all,并选择要添加额外值的NULL值,如下所示:

select PkID , HouseFk , house_extra_id , Price , discount_id, 
NULL AS PacketFk from table_1
union all
select PkID, HouseFk, NULL AS house_extra_id , Price , discount_id, 
PacketFk from table_2

答案 1 :(得分:2)

它会起作用

select  pkid,housefk,house_extra_id,price,discount_id,null as packetfk
from T1

union all

select pkid,housefk,null as house_extra_id,price,discount_id,packetfk
from t2

答案 2 :(得分:1)

SELECT PkID, HouseFK, house_extra_id, Price, discount_id, NULL AS PacketFK FROM tableOne
UNION ALL
SELECT PkID, HouseFK, NULL AS house_extra_id, Price, discount_id, PacketFK FROM tableTwo