doukuang8166 2014-03-21 22:29
浏览 52
已采纳

INNODB:在mysql表之间创建多对多的关系

I have 2 tables, articles and entities table. An article can have many entities and an entity can belong to more than one category.

What would be the sql to create such an association in mysql such that I can insert an entity to the entities table via the articles table and be able to query for the article from the entities table.

The entity only has 2 fields, entity_id and entity while the articles table has 3 fields: article_id, url and category

Is this what I require to do

CREATE TABLE articles(
  article_id  INT NOT NULL AUTO_INCREMENT,
  url VARCHAR(255),
  category VARCHAR(255),
  PRIMARY KEY(article_id)
)ENGINE=INNODB;

CREATE TABLE entities(
  entity_id  INT NOT NULL AUTO_INCREMENT,
  entity VARCHAR(50),
  PRIMARY KEY(entity_id)
)

 CREATE TABLE relationships(
   relationship_id INT NOT NULL AUTO_INCREMENT,
   article_id INT,
   entity_id INT,
   PRIMARY KEY(relationship_id),
   FOREIGN KEY(article_id) references articles(article_id),
   FOREIGN KEY(entity_id) references entities(entity_id)
 )ENGINE=INNODB;
  • 写回答

2条回答 默认 最新

  • dongmei425373 2014-03-21 22:33
    关注

    You need a third table that tracks the relationships between entity_id and article_id. When you want to make or change a relationship, you update this table.

    [edit] This stackoverflow question may help you to understand, especially the most upvoted answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流