Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

sql - Union between nonmatching columns tables

Suppose we have 3 tables as follows:

Table1: Column1, Column2, Column3

Table2: Column1, Column2, Columnxyz, Column3

Table3: Column1, Column2, Column3

I have a view with the following DDL:

CREATE VIEW [dbo].[View1]
  AS (
    SELECT 'Table1' as [Source], * FROM [Table1] 
    UNION
    SELECT 'Table2' as [Source], * FROM [Table2]
    UNION
    SELECT 'Table3' as [Source], * FROM [Table3]
  );

That view works flawlessly assuming all tables have the same columns.

however, in the example above, with table2 having additional column: columnxyz What would I need to change in the view union? In other words, do I have to create Table1 and Table3 with this additional column as well, or can we circumvent this by somehow dynamically appending this extra column in the view to the other tables missing it and filling it with "None" or "N/A" as default data (since Table1 and table2 don't originally have this columnxyz so there's really no data anyways)?

question from:https://stackoverflow.com/questions/65838207/union-between-nonmatching-columns-tables

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Select a constant from the tables without the additional column, exactly the same as you are already doing for [Source]. However you will have to list the columns explicitly since the additional column is not first or last. As a best practice you should always list your columns anyway.

CREATE VIEW [dbo].[View1]
AS (
  SELECT 'Table1' as [Source], Column1, Column2, 'N/A' AS ColumnXYZ, Column3
  FROM [Table1] 
  UNION ALL
  SELECT 'Table2' as [Source], Column1, Column2, ColumnXYZ, Column3
  FROM [Table2]
  UNION ALL
  SELECT 'Table3' as [Source], Column1, Column2, 'N/A' AS ColumnXYZ, Column3
  FROM [Table3]
);

Note, I've used UNION ALL because UNION will attempt to-duplicate your data, which normally you don't want, and it suffers a performance penalty for doing so. Personally I always handle an de-duplication/grouping in other ways.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...