【问题标题】:How to create new table from multi nested join statement?如何从多嵌套连接语句创建新表?
【发布时间】:2019-05-15 22:17:06
【问题描述】:

我正在尝试从多嵌套联接创建一个新表,但不断出现错误:

Incorrect syntax near ')'.

这是连接语句:

select * 
FROM table1
    LEFT JOIN table2
        ON table1.col1 = table2.col1
    FULL OUTER JOIN table3
        ON table3.col1 = table1.col1 
        AND table3.date >= '2017-10-01'

这就是我尝试创建表格的方式:

select * into newtable from (

select * 
    FROM table1
        LEFT JOIN table2
            ON table1.col1 = table2.col1
        FULL OUTER JOIN table3
            ON table3.col1 = table1.col1 
            AND table3.date >= '2017-10-01'
)

我在最后一个附件做错了什么?

【问题讨论】:

  • ) 后面需要一个表别名。
  • @GordonLinoff 你的意思是as x
  • 我会省略as,但它是可选的。
  • 现在我收到了这个错误The column 'column' was specified multiple times for 'x'. 这三个表有很多常见的字段,但有数百个
  • 您需要决定您想要在目标表中使用哪组(唯一)列,而不是只是懒惰并使用*。当然,您不需要在新表中复制三份col1...

标签: sql database join sql-server-2012


【解决方案1】:

我会使用 CTE(通用表表达式):

with
x as (
select * 
    FROM table1
        LEFT JOIN table2
            ON table1.col1 = table2.col1
        FULL OUTER JOIN table3
            ON table3.col1 = table1.col1 
            AND table3.date >= '2017-10-01'
)
select * into newtable from x

【讨论】:

  • 在没有x 的情况下尝试了这个错误An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
  • x 试了一下得到错误Incorrect syntax near 'x'
  • select * into newtable from x
  • 只要确保* 不包含任何重复的列名。看起来至少col1 会引起问题。
  • 这有助于更改错误消息The column 'abc' was specified multiple times for 'x'. 所有三个表都有相同名称的列,但它们位于数百列中。我真的只想将 select 语句的结果而不考虑列名粘贴到新表中,我该怎么做?
【解决方案2】:

您根本不需要子查询。只需使用into

select * 
into newtable
FROM table1
    LEFT JOIN table2
        ON table1.col1 = table2.col1
    FULL OUTER JOIN table3
        ON table3.col1 = table1.col1 
        AND table3.date >= '2017-10-01';

当然,select * 不会真正起作用,因为您的列名必须是唯一的。但我猜你是在你的真实查询中列出它们。

此外,过滤full outer join 中的表也很棘手。为此,我通常会推荐一个子查询。

【讨论】:

  • 如何处理查询中的外连接?新手,但只想要 2017-10-01 以后的记录?
  • @RustyShackleford 。 . .你可能只想要一个left join
  • 这有帮助,但是在这三个表中的许多列是相同的,我被告知我需要将它们列出来,所以想办法解决这个问题。每列有数百列。
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2011-11-03
  • 2023-02-14
  • 1970-01-01
  • 2012-05-07
  • 2020-10-30
  • 1970-01-01
相关资源
最近更新 更多