I’m trying to find an SQL query to end up with 1 row containing an article title and its associated keywords.
Articles
-ArticleID PK
-ArticleTitle
-ArticleBody
Keywords
-KeywordID PK
-Keyword UNIQUE
Keyword_Article
-KeywordID PK
-ArticleID PK
Is this possible without multiple queries in PHP?
What I have which gives me as many rows as there are keywords per article
SELECT Article.ArticleID,
Article.ArticleTitle,
Keywords.Keyword,
Keywords.KeywordID
FROM Article
LEFT JOIN Keyword_Article
ON (Keyword_Article.ArticleID = Article.ArticleID)
LEFT JOIN Keywords
ON (Keyword_Article.KeywordID = Keywords.KeywordID)
WHERE Article.ArticleID='example'
I’m curious to see how and if it can be done with 1 SQL query.
You cannot have a SQL statement that returns a variable number of columns. So, you can’t put each keyword in a separate column where the number of columns would vary by the article (unless you use dynamic SQL).
You can concatenate the keywords together into a single column using
group_concat: