如何使用中间表作为链接从另一个表填充表ID列

时间:2014-03-25 17:46:55

标签: sql join sqlite database-administration insert-select

重新设计数据库布局,我遇到了障碍:

现在名为Items_Old的原始表具有以下3列重要性:

Name | Width | Length

我已经创建了一个名为ItemSizes的新表:

ID | Width | Length

和最后一次调用Items

Name | SizeID

我想弄清楚如何从ItemSizes表格中选择SizeID到Items

where Items_Old.Name = Items.Name and Items_Old.Width = ItemSizes.Width 
      AND Items_Old.Length = ItemSizes.Length

我已经得到了一个SizeID和Items_Old.Name列表,其中包含以下内容:

Select IST.ID , Old.Name
From ItemSizes AS IST, Items_Old AS Old
Where IST.Width = Old.Width 
       And  IST.Length = Old.Length 

但是当我尝试这样的事情时:

Insert Into Items
(SizeID)
Select IST.ID , Old.Name
From ItemSizes AS IST, Items_Old AS Old
Where IST.Width = Old.Width 
       And  IST.Length = Old.Length
Where Items.Name = Info.Name

我得到了一个语法错误,因为第二个我也尝试了

Insert Into Items
(SizeID)
(Select IST.ID , Old.Name
From ItemSizes AS IST, Items_Old AS Old
Where IST.Width = Old.Width 
       And  IST.Length = Old.Length) As Info 
Where Items.Name = Info.Name

但收到错误near "("

1 个答案:

答案 0 :(得分:1)

在UPDATE语句中,您可以使用相关子查询查找值:

UPDATE Items
SET SizeID = (SELECT ID
              FROM ItemSizes
              JOIN Items_Old USING (Width, Length)
              WHERE Name = Items.Name)