【问题标题】:SQL - how to retrieve mutlple rows from a table, and then take that info and dump it into a new row on a different tableSQL - 如何从表中检索多行,然后获取该信息并将其转储到不同表的新行中
【发布时间】:2013-02-14 21:37:19
【问题描述】:

我想根据 typeID 编号从一个表中获取行,并使用来自第一个表查询的数据和一些静态变量的混合数据将新行插入到另一个表中。

有没有简单的方法可以做到这一点?

代码编辑:(我无法让它工作 - 得到一个 MIssing Expression 错误)

Insert into tableOne
(pk_col, Custom_int_col, Data_from_other_col)
Select  default,111,security_resource_id
From security_resource sr
Where sr.company_id = 1

【问题讨论】:

  • 默认是列名,如果是,它也是关键字,所以您需要根据后端的偏好将其包装在 "、[] 或 `s 中
  • 这里的问题是该表有一个 sequence.nextval 函数,所以我不得不为 pk_col 调用 tablename.nextval 而不是使用 default 关键字

标签: sql database insert-into


【解决方案1】:

类似

Insert SomeTable(SomeCol1, SomeCol2,SomeCol29)
Select 'SomeText', SomeCol3,963.45 From SomeOtherTable Where SomeKey = 876

还有另一种风格,称为select into。无法准确了解语法,因为您从未提及您使用的是哪个 DBMS。

【讨论】:

  • 为此使用 oracle sql developer。我会给你的代码一个镜头
【解决方案2】:

是的

    INSERT INTO yourTable
    (column1,column2)
    SELECT '' ,column FROM SecondTa

【讨论】:

    【解决方案3】:

    如果第二个表不存在,您可以使用create table asselect into 创建它,具体取决于您使用的数据库。

    例如:

    select col1, 123 as value
    into NewTable
    from t
    where flag = 0
    

    在某些数据库中,语法为:

    create table as
        select col1, 123 as value
        from t
        where flag = 0
    

    Tony 已经回答了第二张表已经存在的情况。

    【讨论】:

      猜你喜欢
      • 2017-12-11
      • 2020-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多