【问题标题】:SQL Select Into FieldSQL 选择到字段
【发布时间】:2010-12-29 05:58:34
【问题描述】:

我想完成以下任务:

Select DISTINCT(tableA.column) INTO tableB.column FROM tableA

目标是选择一个不同的数据集,然后将该数据插入到新表的特定列中。

【问题讨论】:

    标签: sql distinct select-into


    【解决方案1】:
    SELECT column INTO tableB FROM tableA
    

    SELECT INTO 将在向其中插入新记录时创建一个表。如果这不是您想要的(如果 tableB 已经存在),那么您将需要执行以下操作:

    INSERT INTO tableB (
    column
    )
    SELECT DISTINCT
    column
    FROM tableA
    

    请记住,如果 tableb 的列多于一个列,则需要列出将插入的列(就像我在示例中所做的那样)。

    【讨论】:

      【解决方案2】:

      你已经差不多了。

      SELECT DISTINCT column INTO tableB FROM tableA
      

      它将插入到选择列表中指定的任何列中,因此如果您需要插入到不在tableA 中的tableB 列中,则需要为您的选择值设置别名。

      SELECT INTO

      【讨论】:

        【解决方案3】:

        试试下面...

        INSERT INTO tableB (column)
        Select DISTINCT(tableA.column)
        FROM tableA
        

        【讨论】:

          【解决方案4】:
          目标是选择一个不同的数据集,然后将该数据插入到新表的特定列中。

          我不知道 tableB 的架构是什么...如果表 B 已经存在并且列上没有唯一约束,您可以像其他任何人在这里建议的那样做......

          INSERT INTO tableB (column)Select DISTINCT(tableA.column)FROM tableA

          但是如果您对表 B 有唯一约束并且它已经存在,则您必须排除表 B 中已经存在的那些值...

          INSERT INTO tableB (column)
          Select DISTINCT(tableA.column)
          FROM tableA
          WHERE tableA.column NOT IN (SELECT /* NOTE */ tableB.column FROM tableB)
          -- NOTE: Remember if there is a unique constraint you don't need the more
          -- costly form of a "SELECT DISTICT" in this subquery against tableB
          -- This could be done in a number of different ways - this is just
          -- one version. Best version will depend on size of data in each table,
          -- indexes available, etc. Always prototype different ways and measure perf.

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-06-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-08-09
            相关资源
            最近更新 更多