1

我有如下的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

表_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 列相同

4

3 回答 3

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(列名在 an 的第一个选择中定义UNION)。然后你order by最后,这将影响完整的结果集。

于 2013-10-23T01:37:42.923 回答
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 演示

于 2013-10-23T01:38:31.933 回答
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
于 2013-10-23T02:03:27.457 回答