Sobes.tech
Senior

Describe the library model. There are 3 entities: "Author", "Book", "Reader". Physically, there is only one book and it can only be with one reader. Create tables for the library considering this.

sobes.tech AI

Answer from AI

To describe a library model with entities "Author", "Book", and "Reader" and the condition that each book is unique and can only be with one reader, the following tables can be proposed:

  1. Author
  • id (PK)
  • name
  • other fields (biography, date of birth, etc.)
  1. Book
  • id (PK)
  • title
  • author_id (FK to Author.id)
  • reader_id (FK to Reader.id, nullable)
  1. Reader
  • id (PK)
  • name
  • other fields (contact details, etc.)

Explanation:

  • Each book is linked to one author via author_id.
  • The reader_id field in the books table indicates which reader currently has the book. If the book is not issued, this field is NULL.
  • Since a book can only be with one reader, the "book — reader" relationship is implemented through a foreign key in the books table.

Thus, the model reflects the uniqueness of the book and its belonging to one reader.

Example SQL schema:

CREATE TABLE Author (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255) NOT NULL
);

CREATE TABLE Reader (
  id SERIAL PRIMARY KEY,
  name VARCHAR(255) NOT NULL
);

CREATE TABLE Book (
  id SERIAL PRIMARY KEY,
  title VARCHAR(255) NOT NULL,
  author_id INTEGER NOT NULL REFERENCES Author(id),
  reader_id INTEGER REFERENCES Reader(id)
);