组合两个表而不破坏原始列的内容

时间:2013-10-23 01:29:19

标签: sql database union

我有一个Table_A和Table_B如下所示,我如何创建一个UNION来生成像Table_C这样的结果集,以便保留Table_A和Table_B中列的原始内容。

表-A:

ID    High_Level_Text
-------------------------
01    High Level Text One
02    High Level Text Two
03    High Level Text Thr

表-B:

ID    Key    Low_Level_Text
----------------------------------
01    001    Low Level Text 01/001
01    002    Low Level Text 01/002
01    003    Low Level Text 01/003
02    001    Low Level Text 02/001
03    002    Low Level Text 03/002

Table_C:

ID    Key    High_Level_Text      Low_Level_Text
-------------------------------------------------------
01           High Level Text One
01    001                         Low Level Text 01/001
01    002                         Low Level Text 01/002
01    003                         Low Level Text 01/003
02           High Level Text Two
02    001                         Low Level Text 02/001
03           High Level Text Thr
03    002                         Low Level Text 03/002

在Table_C中,对于没有来自Table_A的原始数据的记录,High_Level_Text列的记录为空,与Table_B的Low_Level_Text和Key列相同

3 个答案:

答案 0 :(得分:2)

你可以这样做:

select a.id as "ID",
  null as "KEY",
  a.High_level_text as "High_level_text",
  null as "Low_Level_Text"
from table_a a
union
select b.id,
  b.key,
  null,
  b.Low_Level_Text
from table_b b
order by 1,  2

sqlfiddle demo

这会在第一个select中设置结果中所需的列(列名在UNION的第一个选择中定义)。然后在结尾处order by,这将影响完整的结果集。

答案 1 :(得分:0)

试试这个:

SELECT ID, NULL as Key, High_Level_Text, NULL as Low_Level_Text
FROM Table_A
UNION
SELECT ID, Key, NULL as High_Level_Text, Low_Level_Text
FROM Table_B
ORDER BY ID

选中此SQL FIDDLE DEMO

答案 2 :(得分:0)

试试这个:

SELECT id, `key` , `low_level_text` , NULL AS `high_level_text`
FROM table_b
UNION ALL
SELECT id, NULL AS `key` , NULL AS `low_level_text` , `high_level_text`
FROM table_a
ORDER BY id ASC