U
U
UNy2018-08-24 01:01:31
MySQL
UNy, 2018-08-24 01:01:31

Many-to-many relationship?

I have 3 tables: Books, Authors and 3 in between to provide a many to many relationship. It's made like this:

CREATE TABLE `m2m_books_authors` (
  `b_id` int(10) unsigned NOT NULL,
  `a_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`b_id`,`a_id`),
  KEY `FK_m2m_books_authors_authors` (`a_id`),
  CONSTRAINT `FK_m2m_books_authors_authors` FOREIGN KEY (`a_id`) REFERENCES `authors` (`a_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `FK_m2m_books_authors_books` FOREIGN KEY (`b_id`) REFERENCES `books` (`b_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8

That is, the a_id and b_id fields are both primary and external at the same time. In this regard, there are a couple of questions:
1) Is it necessary to make them primary in such a table? Maybe it's enough that they are external?
2) There is a duplication of fields in them, i.e. in the record in the a_id field, the same number can occur several times (as in b_id). Why doesn't the duplicate primary key error occur?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2018-08-24
@UNy

1. Optional, you can add an artificial primary key. But then, in order to avoid duplicates, you will have to make a unique key from the same pair of fields.
2. There is no error, because the key is composite. The uniqueness of not individual fields, but a pair is checked.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question