如何将表从独立更新为多对一关系

时间:2018-03-31 19:56:07

标签: mysql sql

我有两张桌子 第一:

---------------------
 ID  Statement 
---------------------
 1   First statement
 2   Another one

第二:

---------------------
 ID  Topic 
---------------------
 1   First topic
 2   Another topic

到目前为止,所有主题的陈述都是不变的。对于每个主题,都显示了所有陈述 现在我希望语句是动态的,并且每个主题都不同,所以我需要Statement表看起来像:

-------------------------------
 ID  Statement          TopicID 
-------------------------------
 1   First statement     1
 2   Another one         1
 3   First statement     2
 4   Another one         2 

怎么能实现呢?

编辑

到目前为止,我能够像这样创建表格:

-------------------------------
 ID  Statement          TopicID 
-------------------------------
 3   First statement     1
 4   Another one         1
 5   First statement     2
 6   Another one         2 

为此,我在ALTER TABLE Statements ADD COLUMN TopicID int(10) UNSIGNED的语句中添加了新列 所以我的桌子看起来像这样:

-------------------------------
 ID  Statement          TopicID 
-------------------------------
 1   First statement     0
 2   Another one         0

下一步是使用INSERT INTO statements (Statement, TopicId) SELECT statements.Statement, topics.ID FROM statements, topics查询填充表格。这种Statements表填充了StatementTopicID数据:

-------------------------------
 ID  Statement          TopicID 
-------------------------------
 1   First statement     0
 2   Another one         0
 3   First statement     1
 4   Another one         1
 5   First statement     2
 6   Another one         2 

最后一步是删除带有statement

错误TopicID的{​​{1}}个DELETE FROM Statements WHERE TopicID = 0

有没有更简单的方法?

0 个答案:

没有答案