Many self relationship representation for many

Asked

Viewed 434 times

0

I am creating an Entity-Relationship Model in which a Student can have many Students, thus characterizing many to many’s self-relationship.

However, I am doubtful how to implement this relationship at the time of the bank’s creation. I must create the Student table and a second table possessing two Student keys?

If it helps, I’m doing this relationship to identify which friends a Student has added within the system.

1 answer

1

Yes, the way to represent a many-to-many relationship is to break it into an intermediary table. For example in Mysql we would do:

create table a(
  id int primary key auto_increment,
  text varchar(60)
);

create table b(
  id int primary key auto_increment,
  text varchar(60)
);

Now the relationship of the tables

create table a_b(
  id int primary key auto_increment,
  a_id int,
  b_id int
  FOREIGN KEY (a_id) REFERENCES a(id),
  FOREIGN KEY (b_id) REFERENCES b(id)
);
  • Does that also apply to relationships? I am aware that indeed M-N cardinality relationships generate a third table, but in the case of an entity only relating to itself I cannot visualize the existence of three tables.

  • 1

    I get it. I think I misunderstood your problem. In this case you can simply put a key pointing to it yourself. It’s okay to do that. Using a lot to create categories that have subcategories or when they want to create the structure of a menu with submenus in the database.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.