a question on many-many relationships
I have the following tables
- items
- similars
- items_similars = pivot table
items->similars has a many-many relationship
the items_similars has the following field
- item_id
- similar_id
if I am using InnoDB as my engine, do I need to create a relation betwee开发者_JAVA技巧n items.id and items_similars.id? or between similars.id and items_similars.id? or even both?
are there advantages in doing or in not doing so?
Many-to-many relationships, AFAIK, can only be implemented via transition tables (pivot tables) in RDBMS. The "items_similar" table should have at least "items_id" and "similar_id" which are foreign keys from the "items" and "similars" tables' primary keys.
CREATE TABLE item_similar
(
item_id int NOT NULL
,similar_id int NOT NULL
,PRIMARY KEY ( item_id, similar_id )
,FOREIGN KEY ( item_id ) REFERENCES item ( item_id ) ON UPDATE CASCADE
ON DELETE NO ACTION
,FOREIGN KEY ( similar_id ) REFERENCES similar ( similar_id ) ON UPDATE CASCADE
ON DELETE NO ACTION
)
精彩评论