Unitech
Unitech

Reputation: 5981

Get articles and comments with only one SQL query ? (one to many relation)

I have one table named 'articles' and other one linked with it named 'comments'.

articles ------------ comments

Is there a SQL query to get all articles and their comments linked with it ?

articles1
  +------ comment1
  +------ comment2
  +------ comment3
articles2
  +------- comment4
  +------- comment5

Thanks

Upvotes: 1

Views: 417

Answers (3)

Conrad Frix
Conrad Frix

Reputation: 52675

Here's a Stackexchange query that lists posts with its Comments. You'll notice its uses a LEFT JOIN

SELECT  top 100 p.id [Post Link], p.id, c.id, c.text from posts p
LEFT JOIN comments c
on p.id = c.postid

This is because every post is not guaranteed to have a Comment

Upvotes: 0

user330315
user330315

Reputation:

You failed to post more details about your tables, but here is a blind guess from my side:

SELECT articles.*, 
       comments.comment
FROM articles 
   JOIN comments ON comments.article_id = articles.id

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85096

Seems like a JOIN would fit your needs:

SELECT * FROM Articles as a
INNER JOIN comments as c
ON a.articleId = c.ArticleId

Take a look at this article. It gives the best explanation of JOINS that I have seen.

Upvotes: 2

Related Questions