mysql - 创建一个新的连接表以反射(reflect)连接表之一中的两列主键

标签 mysql sql

在 MYSQL 数据库中,我需要为多对多关系创建一个新的联结表,以反射(reflect)关系中的一个表具有两列复合主键这一事实。 如何编写 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 表中每一行的唯一标识符。这是否澄清了问题?

最佳答案

因此,根据我收集的信息,我认为您正在寻找的是:

INSERT INTO newjunction 
SELECT o.keyword, d.id, d.effectiveTime
  FROM description d
  JOIN oldjunction o
    ON o.descriptionid = d.id

此外,我认为 newjunction 缺少 FK 到 wordkeys 表。

关于mysql - 创建一个新的连接表以反射(reflect)连接表之一中的两列主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23438118/

相关文章:

mysql - 查找至少有 2 行的值为 x 的条目

mysql - 无法保存存储过程 : #1064 - You have an error in your SQL syntax;

php - 如何使用 php web 服务从 MySql 中的 2 个不同表中获取数据

sql - 如何编写一个SQL语句以将 "LIKE"用于9个不同的值?

sql - 如何将特定行保留为查询 (T-SQL) 的第一个结果?

Mysql::错误:表 'table_name' 被标记为崩溃,应该修复

php - BLOB 优于 varchar?

sql - 此处不允许使用分组功能

php - 为什么这容易发生 SQL 注入(inject)?

c# - 允许 SQL Server 代理的 Excel 权限