I am wanting to create a new view based on joining three tables.
table 1 and table 2 have the same column names but the data in them is representative of different time frames. The third table has columns that are unique in both tables.
My query takes all data of table1 and uses a column in table 1 to extract all records from table 2 that have a match.
and then merge this combined dataset with the third table where ever date is greater than '2017-12-01'
SELECT *
FROM table1
LEFT JOIN table2
ON table1.lookup_column = table2.lookup_column
LEFT JOIN table3
ON table3.lookup_column = table1.lookup_column
AND table3.date >= '2017-10-01'
When I run this query to create the new view
select * into new_table
FROM table1
LEFT JOIN table2
ON table1.lookup_column = table2.lookup_column
LEFT JOIN table3
ON table3.lookup_column = table1.lookup_column
AND table3.date >= '2017-10-01'
I get the error :
Column names in each table must be unique. Column name 'abc' in table 'new_table' is specified more than once.
How can I avoid this problem between the two tables where the column names are the exactly the same? or how can I specify that I want to combine table 1 and table 2 on column names?
Edit:
input
table 1 table2 table
col1 col2 col1 col2 col3 col4
abc def ghi jkl mno pqr
Output:
col1 col2 col3 col4
abc def mno pqr
ghi jkl mno pqr
4条答案
按热度按时间iyfjxgzm1#
You have to set different names for each column in
table1
andtable2
that you want to copy innew_table
. For example:xggvc2p62#
Looking at the expected output, and the fact that table1 and table2 are structurally identical, you probably want
UNION
:guz6ccqo3#
Seeing your sample data and output wanted, that doesn't have anything to do with joining 3 tables and left joins.
You can see a demo here.
However, your sample data is insufficient to point out expected gotcha. A cross join is a dangerous one if you use without knowing what you are doing.
7cjasjjr4#
By select * into [something] you are creating a new table.
You could do this to create a view:
Then you could use the view by: