需要使用新PK重复更新FK

时间:2013-01-13 12:34:26

标签: php mysql foreign-keys primary-key

我有两张桌子 - 今晚我真的相信我有一个金发碧眼的时刻。

标题

HeadingID, HeadingName, TopicID

副标题

SubHeadingID, SubHeadingName, HeadingID

我想要做的是复制标题中的所有条目和SubHeadings TopicID = 1 = = 2。

我写过:

INSERT INTO Headings (HeadingName, TopicID)
SELECT HeadingName, 2 FROM Headings WHERE TopicID = 1  //(Duplicating Headings and assigning TopicID 2).

我被困在SubHeadings;我想加入刚刚创建的新HeadingID并且我不知道。我可以使用相同的Insert / Select语句来完成其余的字段,但是我很难过。

有人可以帮我一个例子或一些文件吗?

简化数据如下所示:

HeadingID = 1
HeadingName = 'News'
TopicID = 1
HeadingID = 2
HeadingName = 'Sport'
TopicID = 1

SubHeadingID = 1
SubHeadingName = 'Local'
HeadingID = 1
SubHeadingID = 2
SubHeadingName = 'National'
HeadingID = 1
SubHeadingID = 3
SubHeadingName = 'International'
HeadingID = 1
SubHeadingID = 4
SubHeadingName = 'Baseball'
HeadingID = 2
SubHeadingID = 5
SubHeadingName = 'Cricket'
HeadingID = 2

1 个答案:

答案 0 :(得分:0)

以下查询将帮助您:)

INSERT INTO SubHeadings (SubHeadingName, HeadingID) 
SELECT subhdng.SubHeadingName, hdng.HeadingID 
FROM Headings hdng
INNER JOIN SubHeadings subhdng ON hdng.HeadingID = subhdng.HeadingID 
WHERE hdng.TopicID = 2