My DB has three tables:
CREATE TABLE Users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
);
CREATE TABLE Categories (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
user_id INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES Users(Id)
);
CREATE TABLE Notes (
id INTEGER PRIMARY KEY,
description TEXT NOT NULL,
category_id INTEGER,
user_id INTEGER NOT NULL,
FOREIGN KEY (category_id) REFERENCES Categories(Id),
FOREIGN KEY (user_id) REFERENCES Users(Id)
);
I want to implement functionality to get user an ability to share note he created with another user. I ended up with a solution to have junction table:
CREATE TABLE SharedNoteToUserId
(
note_id int NOT NULL,
user_id int NOT NULL,
CONSTRAINT PK_SharedNoteToUserId PRIMARY KEY
(
note_id,
user_id
),
FOREIGN KEY (note_id) REFERENCES Notes(Id),
FOREIGN KEY (user_id) REFERENCES Users(Id)
);
But I also want to have endpoint to retrieve list of all categories including categories from shared notes. It looks like it’s just union of two tables:
SELECT Categories.id, Categories.name
FROM Categories
WHERE Categories.user_id = 2
UNION
SELECT Categories.id, Categories.name
FROM SharedNoteToUserId
JOIN Notes ON Notes.id = SharedNoteToUserId.note_id
JOIN Categories ON Categories.id = Notes.category_id
WHERE SharedNoteToUserId.user_id = 2;
But I’m not sure that it’s a right approach. Maybe I need to create and manage separate junction table for categories as well?
Sergey K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.