I have a simple article and comments system with the following tables:
Articles table:
id | writer | text
1 | Bob | first article
2 | Marley | second article
Comments table:
id | article_id | comment
1 | 1 | i love this article
2 | 1 | good one
3 | 2 | waiting for more
I want to select each article with its comments underneath it. I use the following query:
SELECT * FROM articles LEFT JOIN comments ON articles.id = comments.article_id
The results I get:
articles.id | articles.writer | articles.text | comments.id | comments.article_id | comments.comment
1 | Bob | first article | 1 | 1 | i love this article
1 | Bob | first article | 2 | 1 | good one
2 | Marley | second article | 3 | 2 | waiting for more
What I want:
articles.id | articles.writer | articles.text | comments.id | comments.article_id | comments.comment
1 | Bob | first article | 1 | 1 | i love this article
NULL | NULL | NULL | 2 | 1 | good one
2 | Marley | second article | 3 | 2 | waiting for more
So how do I select each article with its comments and display the article only once not with each comment
Thanks
You can use user variables in MySQL to do this:
See SQL Fiddle with Demo.
The result is:
Edit, if you need the
comment.id, then you can add it to the result:See SQL Fiddle with Demo. The result is: