Microsoft Access SQL逗号分隔值

时间:2017-12-04 17:17:57

标签: sql ms-access split comma

我有一个名为authors的主键和一个名为books的字段的数据集。

表格如下所示:

Authors (primary key)     Books
John                      Fathom,Mouseover,Keycard
Kyle                      Teachers,Carl,Phone

我知道这违反了1NF,我正在尝试创建一个新表(一对多关系),主键(作者)每本书出现不止一次。即

Authors                   Books
John                      Fathom
John                      Mouseover
John                      Keycard
Kyle                      Teachers
Kyle                      Carl
Kyle                      Phone

我需要在微软访问中使用SQL,我认为它涉及拆分功能,但我对如何执行此查询感到茫然。

非常感谢任何见解!

非常感谢

1 个答案:

答案 0 :(得分:0)

好吧,既然代码很难实现,而你只有2代码,我想我可以分享一个已实现的解决方案:

(将MyTable替换为您的表名,并使用正确的名称查找并替换所有字段名称:

SELECT * Into NewTable FROM (
SELECT Author, IIf(InStr(1, [Books], ',') = -1, [Books], Left([Books], InStr(1, [Books], ',') - 1)) As Book
FROM MyTable
WHERE IIf(InStr(1, [Books], ',') = -1, [Books], Left([Books], InStr(1, [Books], ',') - 1)) <> ""
UNION ALL
SELECT Author, IIf( InStr(1,[Books],',')> 0, IIf(InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(1,[Books],',') + Len(',')), Mid([Books], InStr(1,[Books],',') + Len(','), InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') - InStr(1,[Books],',') - Len(','))), "")  As Book
FROM MyTable
WHERE IIf( InStr(1,[Books],',')> 0, IIf(InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(1,[Books],',') + Len(',')), Mid([Books], InStr(1,[Books],',') + Len(','), InStr(InStr(1,[Books],',') + Len(','), [Books] , ',') - InStr(1,[Books],',') - Len(','))), "")  <> ""
UNION ALL
SELECT Author, IIf( InStr(InStr(1,[Books],',') + Len(','), [Books],',')> 0, IIf(InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(',')), Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') - InStr(InStr(1,[Books],',') + Len(','), [Books],',') - Len(','))), "")  As Book
FROM MyTable
WHERE IIf( InStr(InStr(1,[Books],',') + Len(','), [Books],',')> 0, IIf(InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') < 1, Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(',')), Mid([Books], InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), InStr(InStr(InStr(1,[Books],',') + Len(','), [Books],',') + Len(','), [Books] , ',') - InStr(InStr(1,[Books],',') + Len(','), [Books],',') - Len(','))), "") <> ""
)