我把表结合起来:
PkID | HouseFk | house_extra_id | Price | discount_id
1 | 5 | 6 | 1205 | 0
PkID | HouseFk | PacketFk | Price | discount_id
1 | 6 | 7 | 500 | 0
像这样使用union all
:
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
结果是:
PkID | HouseFk | house_extra_id | Price | discount_id | PacketFk
1 | 5 | 6 | 1205 | 0 | NULL
1 | 6 | NULL | 500 | 0 | 7
但是,如果我需要两个单独的“价格”列,具体取决于它与哪个表合并?所以最后我的表看起来像:
PkID | HouseFk | house_extra_id | t1_Price | t2_Price | discount_id | PacketFk
1 | 5 | 6 | 1205 | NULL | 0 | NULL
1 | 6 | NULL | NULL | 500 | 0 | 7
答案 0 :(得分:5)
您可以使用更多列,例如:
select pkid, housefk, house_extra_id,
price AS t1_Price, NULL AS t2_Price,
discount_id, null as packetfk
from T1
union all
select pkid, housefk, null as house_extra_id,
NULL AS t1_Price, price AS t2_Price,
discount_id, packetfk
from t2