I am creating a database where a user can add many books. And a book can be read by many users. I'm using PostgreSQL and set up the following structure:
CREATE TABLE users(
uid SERIAL PRIMARY KEY,
email VARCHAR(25) UNIQUE NOT NULL,
hash TEXT NOT NULL,
first_name VARCHAR(30),
last_name VARCHAR(80)
);
CREATE TABLE books(
bid VARCHAR(30) PRIMARY KEY,
title VARCHAR(40) NOT NULL,
author VARCHAR(40) NOT NULL,
thumbnail TEXT
);
CREATE TABLE users_books(
user_id INTEGER NOT NULL,
book_id VARCHAR(30) NOT NULL,
date_added DATE NOT NULL DEFAULT CURRENT_DATE,
PRIMARY KEY (user_id, book_id),
FOREIGN KEY (user_id) REFERENCES users(uid) ON UPDATE CASCADE,
FOREIGN KEY (book_id) REFERENCES books(bid) ON UPDATE CASCADE
);
As I'm not very familiar with databases, I have the following questions:
- In the
users_books
table, does the use ofPRIMARY KEY (user_id, book_id)
dispense with the use ofuser_id
column or is it still mandatory? - Is there any way to auto-populate a table according to the information received by another table? For example, if I feed the users and books tables, can the users_books table feed itself?
- Is it recommended that I use 3 tables to achieve this goal of people adding books? Or the most recommendable would be to use 2 tables?
Finally, I would like to know what you would do differently from this.