'how to validate id and ensure that is found in another table before inserting data using SQL

I have three tables first table for articles

id content
1 dummy content_1
2 dummy content_2
3 dummy content_3
4 dummy content_4
5 dummy content_5

and another for categories

id category_name slug
1 movies movies
2 men health men-health
3 tech tech
4 games games
5 food food

and third table for defining categories for each article

article_id category_id
1 5
2 5
2 1
2 3
3 5
3 1

and i am using normal insert statement to insert data into third table and while inserting the IDs into the third table i want to validate if they found in first and second table i.e if i am inserting the following row

article_id category_id
3 1

i want to check if there is article id 3 and there is category id 1 in one query and if one of them not found cancel the insertion process how i write a query for this ?



Solution 1:[1]

first of all make the id column primary key on each tables categories and articles

ALTER TABLE categories
ADD PRIMARY KEY (ID);

ALTER TABLE articles
ADD PRIMARY KEY (ID);

just add a foreign key constraint for the two columns

ALTER TABLE article_category
ADD FOREIGN KEY (category_id) REFERENCES categories(id);

ALTER TABLE article_category
ADD FOREIGN KEY (article_id) REFERENCES articles(id);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1