I have a table called Articles. I also have a table for Tags. The tags table actually has 2 separate tables as its a many-to-many relationship between Articles and Tags. For example:
CREATE TABLE Articles (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT
title VARCHAR(255),
author INT UNSIGNED NOT NULL,
body TEXT NOT NULL -- column type may not be representative
) Engine=InnoDB;
CREATE TABLE Tags (
id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(32)
) Engine=InnoDB;
CREATE TABLE Article_Tags (
article INT UNSIGNED NOT NULL,
tag INT UNSIGNED NOT NULL,
FOREIGN KEY (article) REFERENCES Articles (id),
FOREIGN KEY (tag) REFERENCES Tags (id)
) Engine=InnoDB;
Now, is it possible to do a single query to return an article, and also all the tags related to that article from the Tags table in the same query?
As per comments, you typically use a
JOINstatement to combine related records from multiple tables.Note that I assume that
Articleshas anIDcolumnArticle_Tagshas anArticleIDandTagIDcolumnTagshas anIDcolumnIf the actual column names differ, you should replace the corresponding columns in my statement with their actual names.
SQL Statement
More information about the JOIN syntax