I would like to start a simple wikepedia database system using postgreSQL with the following,
CREATE TABLE users (
id SERIAL PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
);
CREATE TABLE categories (
id SERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL
);
CREATE TABLE articles (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT now(),
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE
);
CREATE TABLE categories_articles (
category_id INTEGER REFERENCES categories(id) ON DELETE CASCADE,
article_id INTEGER REFERENCES articles(id) ON DELETE CASCADE,
PRIMARY KEY (category_id, article_id)
);
+----------+ +------------+
| users | | articles |
+----------+ +------------+
| id |------->| id |
| username | | title |
| email | | content |
| password | | created_at |
+----------+ | user_id |
+------------+
+-----------+ +------------+
| categories| | articles |
+-----------+ +------------+
| id |------> | id |
| name | | title |
+-----------+ | content |
| created_at |
| user_id |
+------------+
+---------------------+
| categories_articles |
+---------------------+
| category_id |
| article_id |
+---------------------+
- To use the categories_articles table in SQL, you can use SQL statements to insert, update, and delete rows in the table. Here are a few examples:
- To insert a row into the categories_articles table linking an article with ID 1 to a category with ID 2:
INSERT INTO categories_articles (category_id, article_id) VALUES (2, 1);
- To update the category of an article in the categories_articles table, assuming the article has ID 1 and you want to change its category to the one with ID 3:
UPDATE categories_articles SET category_id = 3 WHERE article_id = 1;
- To delete a row from the categories_articles table linking an article with ID 1 to a category with ID 2:
DELETE FROM categories_articles WHERE category_id = 2 AND article_id = 1;
Note that when you insert or update a row in the categories_articles table, you need to make sure that the category_id and article_id values you are inserting or updating correspond to valid categories and articles that exist in the categories and articles tables.
- You may want to use SQL joins to select data from these tables, as well as the categories_articles table, based on certain criteria. For example, to select all articles that belong to a certain category, you could use a query like this:
SELECT articles.title, articles.content
FROM articles
JOIN categories_articles ON articles.id = categories_articles.article_id
WHERE categories_articles.category_id = 2;
This query selects the title and content columns from the articles table, and joins it with the categories_articles table on the id and article_id columns. The WHERE clause filters the results to only include articles that belong to the category with ID 2.