简体   繁体   English

合并两个表并重命名表特定的列

[英]Union two tables and rename table specific columns

I combine the tables: 我合并表格:

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

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

using union all like so: 使用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

result is: 结果是:

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

But what if I want two separate "Price" columns depending from which table it was combined? 但是,如果我想要两个单独的“价格”列,具体取决于合并的是哪个表呢? So that in the end my table looks like: 最终,我的表如下所示:

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

You can use even more columns, like: 您可以使用更多列,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM