Should junction tables have more than one primary keys from another indentifying table?

扶醉桌前 提交于 2019-12-01 11:20:38

each table should only have one primary key which is only about this table. If you then want a second column in Table A containing the values of the table B primary key thats find. Just set up a second index to get performance if requires

Originally I have 3 tables.

Ok.

Table B references Table A. So now Table B has two primary keys. One used as the original primary key and the other one to enforce its relationship with Tabe A.

No. Table B has one primary key and one foreign key. The foreign key might be part of the primary key, and it might not.

Then I want Table B to have a many-to-many relationship with Table X.

Ok.

As I'm adding the relationship, MySQL Workbench added Table Y with both of Table B primary keys and one primary key in Table X. So Table Y now has three primary keys.

A many-to-many relationship is typically implemented as a table that contains two foreign keys as its primary key. In your case, one foreign key is the primary key of Table B, and the other foreign key is the primary key of Table X. The primary key of Table B seems to contain two columns. The tables might look like this.

  • Table A: {a1, a2}
  • Table B: {b1, a1, b2, b3}, a1 references Table A
  • Table X: {x1, x2}

Table Y, which implements the m:n relationship, contains the keys from B and from X.

  • Table Y: {b1, a1, x1}, the two columns b1, a1 reference Table B; the column x1 references Table X

If you want better answers, edit your question and include the SQL DDL for your tables. Get the DDL by using SHOW CREATE TABLE.

You can not have more than one primary key. What you have there might be indexes. If the user_id column from table posts is included in your primary key, you can take it out and leave the primary key composed of just the id column.

I hope this helps

From your edited post - the only way to do this correctly is to have another table to hold the many to many relationship. Sniipit & snippit_topic have single primary keys and this new table has two columns with each of the primary keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!