我的两张表是:
PkID | HouseFk | house_extra_id | Price | discount_id
1 | 5 | 6 | 1205 | 0
PkID | HouseFk | PacketFk | Price | discount_id
1 | 6 | 7 | 500 | 0
如何将这两者合并到一个新表中,该表未存储在数据库中但仅用于输出。我已经尝试了join
和union 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
会遗漏一些列!
答案 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