在MYSQL数据库中,我需要为多对多关系创建一个新的联结表,以反映关系中的一个表具有两列复合主键的事实。 如何编写SQL来实现此目的?
这是当前的表结构:
wordkeys
keyword (pk)
description
id
effectiveTime
other columns
primary key (id, effectiveTime)
oldjunction
keyword (fk to wordkeys)
descriptionid (fk to description)//this needs to change to add effectiveTime
primary key (keyword, descriptionid)//this needs to change to add effectiveTime
newjunction (need to create this table as a function of the others above)
keyword (fk to wordkeys table)
descriptionid
effectiveTime
primary key (keyword, descriptionid, effectiveTime)
foreign key (descriptionid, effectiveTime) to description table
SQL需要完成以下任务:
FOR EACH row in oldjunction
1.) get all the values of effectiveTime associated with the given descriptionid from that row
2.) FOR EACH value of effectiveTime from step 1, create a new row in newjunction table
编辑:
在回应评论时,我正在增加以下信息:
我需要帮助将上面原始帖子的FOR EACH
组件翻译成SQL语法。这将需要创建newjunction
表。我们需要newjunction
表的原因是descriptionid
单独不能唯一地标识description
表中的各个行。相反,我们需要descriptionid
和effectiveTime
的组合,以便为description
表中的每一行获取唯一标识符。这是否澄清了这个问题?
答案 0 :(得分:1)
所以从我收集的内容来看,我认为你正在寻找的是:
INSERT INTO newjunction
SELECT o.keyword, d.id, d.effectiveTime
FROM description d
JOIN oldjunction o
ON o.descriptionid = d.id
另外我认为newjunction
缺少FK到wordkeys
表。