【问题标题】:Combine two tables without ruin the content of original columns合并两个表而不破坏原始列的内容
【发布时间】:2013-10-23 01:29:19
【问题描述】:

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

【问题讨论】:

    标签: sql database union


    【解决方案1】:

    你可以这样做:

    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,这会影响整个结果集。

    【讨论】:

    【解决方案2】:

    试试这个:

    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

    【讨论】:

      【解决方案3】:

      试试这个:

      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
      

      【讨论】:

        猜你喜欢
        • 2019-07-31
        • 2013-07-27
        • 2011-11-11
        • 2010-11-22
        • 2012-10-14
        • 2012-11-11
        • 1970-01-01
        相关资源
        最近更新 更多