如何从表中选择记录并添加到另一个表中一对多

时间:2013-09-23 01:45:22

标签: sql sql-server

我有一个名为logentry的表,它与一个名为logentryfiles的表有一对多的关系。以下是日志条目的表结构。基本上我正在规范我的数据库,我需要从现有的logentry表中填充新表。我在编写SQL语句时遇到了困难。

logentry table

id
outfilename
outfilestoredname
jsonfilename
jsonfilestoredname
logfilename
logfilestoredname

logfiles table

id
filename
filestoredname
fileextension
logentry_id

logentry表中的示例数据

ID 1
jsonfilename E:\EP3\loadlist\5252012CTRLChagasSyphLL.JSON
jsonfilestoredname E:\RunLog\App_Data\uploads\2012\May\31\29fe57db-f159-4f29-8ce1-609c46671aa9.json
outfilename  E:\HIVLoadlist80.out
outfilestoredname E:\RunLog\App_Data\uploads\2012\Jul\26\f691a988-5197-4171-aa49-027b6b7c6242.out
logfilename C:\Users\larsemm\Documents\Outside Work\Reliability Database Testing Files\ICQ Log\Log File 1\Server_051713-154319_Results.log
logfilestoredname E:\RunLogTest\App_Data\uploads\2013\Sep\11\72c62705-6c28-4efc-bb53-f45c381be9dd.log

因此,上述数据在logfiles表中将如下所示

id  1
logentry_id 2
storedfilename  E:\RunLog\App_Data\uploads\2012\May\31\29fe57db-f159-4f29-8ce1-609c46671aa9.json
filename E:\EP3\loadlist\5252012CTRLChagasSyphLL.JSON
fileextension JSON

第二行

id  2
logentry_id 2
storedfilename  E:\RunLog\App_Data\uploads\2012\Jul\26\f691a988-5197-4171-aa49-027b6b7c6242.out
filename  E:\HIVLoadlist80.out
fileextension OUT

等等。

1 个答案:

答案 0 :(得分:1)

INSERT INTO logfiles (filename
,filestoredname
,fileextension
,logentry_id)

SELECT 
,jsonfilename AS filename
,jsonfilestoredname AS storedname
,'JSON' AS extension
,id
FROM logentry L
UNION
SELECT 
,outfilename AS filename
,outfilestoredname AS storedname
,'OUT' AS extension
,id
FROM logentry L
UNION
SELECT 
,logfilename AS filename
,logfilestoredname AS storedname
,'LOG' AS extension
,id
FROM logentry L