繁体   English   中英

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

[英]How to insert values in a single table from two different source tables

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

表 1:ID|CreationTime|serialNum|Caption|

表2:ID|创建时间|业务|案例|报表项|

我想让我的新表具有以下值。

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

请帮我解决。

您可以尝试使用 Left 或 inner join 类似的方法来插入两个表中的数据。

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

这会出错,您的查询将无法正常运行。

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'

在 Union 或 union 中都需要相同长度的列,否则查询失败谢谢

您可以尝试以下查询。

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'

您可以尝试以下查询。

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

暂无
暂无

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

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