Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL one-to-many

I am trying to build an SQL schema for a system where we have channels, each with an id, and one or more fixtures. I am having difficulty finding a way to implement this one-to-many mapping. (i.e. One channel to many fixtures). I am using the H2 database engine.

I cannot have a table :

 id | fixture
----|----------
  1 |    1
  1 |    2
  2 |    3

CREATE TABLE channel(
  id INT NOT NULL PRIMARY KEY,
  fixture INT NOT NULL
  );

... as the PRIMARY KEY id must be UNIQUE.

Similarly, I cannot map as follows:

CREATE TABLE channel(
  id INT NOT NULL PRIMARY KEY,
  f_set INT NOT NULL REFERENCES fixtures(f_set)
  );

CREATE TABLE fixtures(
  id INT NOT NULL PRIMARY KEY,
  f_set INT NOT NULL
  );

... as this required f_set to be UNIQUE

I am currently implementing it as follows:

CREATE TABLE channel(
  id INT NOT NULL PRIMARY KEY,
  f_set INT NOT NULL REFERENCES fixture_set(id)
  );

CREATE TABLE fixtures(
  id INT NOT NULL PRIMARY KEY,
  f_set INT NOT NULL REFERENCES fixture_set(id)
  );

CREATE TABLE fixture_set(
  id INT NOT NULL PRIMARY KEY
  );

... but this means that we can have a channel with a fixture_set which does not have any assigned fixtures (Not ideal).

I was wondering if you had any suggestions for how i may approach this (Or where my understanding is wrong). Thanks

like image 970
ChrisSSocha Avatar asked Dec 21 '22 05:12

ChrisSSocha


1 Answers

"One-to-many" means that many items (may) reference one item. If it's one channel to many fixtures, then fixtures should reference channels, not the other way round, which means the reference column should be in the fixtures table:

CREATE TABLE channel(
  id INT NOT NULL PRIMARY KEY
  );

CREATE TABLE fixtures(
  id INT NOT NULL PRIMARY KEY,
  channel_id INT NOT NULL FOREIGN KEY REFERENCES channel (id)
  );
like image 59
Andriy M Avatar answered Jan 09 '23 09:01

Andriy M