如何在来自两个不同源表的单个表中插入值

时间:2019-01-11 18:02:53

标签: sql sql-server

我的数据库中有两个具有唯一列名的不同表。我想将值添加到我的新表中,该表已经用这两个表中需要的列名创建了。

  

表1:ID | CreationTime | serialNum |标题|

     

表2:ID | CreationTime | Business | Case | ReportItem |

我希望新表具有以下值。

  

表3:ID | CreationTime | serialNum | Business | Case | ReportItem |

我正在尝试使用我知道不正确的查询。

insert into Table3([ID],[creationtime],[Business],[ReportingItem],[Case],[SerialNum])    
select [ID],[creationtime],[Business],[ReportItem],[Case]
from [Table2]     
where creationtime>='1-jan-2018' and creationtime<'2-jan-2018'

union

Select[SerialNum]    
from [Table1]     
where creationtimeutc>='1-jan-2018' and creationtime<'2-jan-2018'

请帮助我解决它。

4 个答案:

答案 0 :(得分:0)

您可以尝试使用Left或内部联接之类的方法从两个表中插入数据。

INSERT INTO user (id, name, username, opted_in)
  SELECT id, name, username, opted_in 
  FROM user LEFT JOIN user_permission AS userPerm ON user.id = userPerm.user_id

在这里,您应该在所有联合查询集中写入相同的结果,即列和数据类型。此处已对此进行了描述。

正确的方法

INSERT INTO #Temp1
SELECT val1, val2 
FROM TABLE1
 UNION
SELECT val1, val2
FROM TABLE2

错误的方式

INSERT INTO #Temp1
SELECT val1, val2 
FROM TABLE1
 UNION
SELECT val2
FROM TABLE2

这将产生错误,并且您的查询将无法正常运行。

答案 1 :(得分:0)

insert into Table3([ID],[creationtime],[Business],[ReportingItem],[Case],[SerialNum])

select [ID],[creationtime],[Business],[ReportItem],[Case]
from [Table2] 
where creationtime>='1-jan-2018' and creationtime<'2-jan-2018'
union
Select null Id, null creationtime, null business, null reportingitem, [SerialNum]
from [Table1] 
where creationtimeutc>='1-jan-2018' and creationtime<'2-jan-2018'

联合或联合中的所有列都需要相同的长度,否则查询失败  谢谢

答案 2 :(得分:0)

您可以尝试以下查询。

insert into Table3([ID],[creationtime],[Business],[ReportingItem],[Case],SerialNum])select [ID],[creationtime],[Business],[ReportItem],[Case],null as [SerialNum]from [Table2] where creationtime>='1-jan-2018' and creationtime<'2-jan-2018'
union Select null as Id, null as creationtime, null as business, null as reportingitem, null as case,[SerialNum]from [Table1] where creationtimeutc>='1-jan-2018' and creationtime<'2-jan-2018'

答案 3 :(得分:0)

您可以尝试以下查询。

CREATE TABLE #TableOUTPUT
(
    ID int,
    creationtime datetime,
    serialNum VARCHAR(10),
    Business  varchar(10),
    [Case] varchar(10),
    ReportItem int

)
GO
CREATE TABLE TableFIRST
(
    ID int,
    creationtime datetime,
    serialNum VARCHAR(10),
    Caption varchar(10)


)
CREATE TABLE TableSECOND
(
    id int,
     creationtime datetime,
    Business varchar(10),
    [Case] varchar(10),
    ReportItem varchar(10)
)

GO
 insert into #TableOUTPUT
 SELECT T1.ID,T1.creationtime,T1.serialNum,T2.Business,T2.[Case],T2.ReportItem FROM TableFIRST T1 INNER JOIN TableSECOND T2 ON T1.ID=T2.ID 
 SELECT * FROM #TableOUTPUT
相关问题