繁体   English   中英

如何将两个具有完全相同的列名的表与具有唯一列名的第三个表联接起来以创建新视图?

[英]How to join two tables that are exactly the same column names with third table with unique column names to create new view?

我想基于联接三个表创建一个新视图。

表1和表2具有相同的列名,但其中的数据代表不同的时间范围。 第三个表具有在两个表中唯一的列。

我的查询获取表1的所有数据,并使用表1中的列从表2中提取具有匹配项的所有记录。

然后将此合并的数据集与日期大于“ 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' 

当我运行此查询以创建新视图时

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'

我得到错误:

Column names in each table must be unique. Column name 'abc' in table 'new_table' is specified more than once.

如何避免列名完全相同的两个表之间出现此问题? 或者如何指定要在列名上合并表1和表2?

编辑:

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

您必须为要复制到new_table中的table1table2中的每一列设置不同的名称。 例如:

select table1.field1 as T1, table2.field1 as T2,
       table1.field2 as T3, table2.field2 as T4
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'

查看预期的输出以及table1和table2在结构上相同的事实,您可能需要UNION

SELECT table1.foo, table1.bar, table3.*
FROM      table1
LEFT JOIN table2 ON table1.lookup_column = table2.lookup_column
LEFT JOIN table3 ON table1.lookup_column = table3.lookup_column AND table3.date >= '2017-10-01'

UNION ALL

SELECT table2.foo, NULL,       table3.*
FROM      table1
LEFT JOIN table2 ON table1.lookup_column = table2.lookup_column
LEFT JOIN table3 ON table1.lookup_column = table3.lookup_column AND table3.date >= '2017-10-01'

通过在[something]中选择*,可以创建一个新表。

您可以这样做来创建视图:

创建视图[dbo]。[ViewName]

选择 *

从表1

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';

然后,您可以通过以下方式使用视图:

从[ViewName]中选择*;

看到所需的示例数据和输出,这与联接3个表和左联接没有任何关系。

select * 
from table1
cross join table3
union all
select * 
from table2
cross join table3;

您可以在此处查看演示。

但是,您的样本数据不足以指出预期的陷阱。 如果不知道自己在做什么,使用交叉连接是很危险的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM