user1020317
user1020317

Reputation: 654

Mysql LEFT JOIN: Limit parent table

I'm trying to get results from DB, but limit the results to the right

SELECT posts.text, comments.text 
FROM posts 
LEFT JOIN comments ON comments.postid= post.id 
Limit 0,5 

The above will return 5 comments of the first post if there is five comments. However I want to return ALL comments, but stop the query after 5 posts. How do I go about this?


Sorry my question was a bit unclear at the start as I wrote the LEFT JOIN wrong..

This is the solution to my problem:

SELECT posts.text, comments.text 
FROM ( SELECT * FROM posts Limit 0,5 ) 
LEFT JOIN comments ON comments.postid= post.id 

One other question. I have only specified posts.text as a select column but will all columns now be returned as "*" is included in the sub query?

Upvotes: 3

Views: 1638

Answers (1)

John Woo
John Woo

Reputation: 263733

if that's what you want, use a subquery to get only 5 parents.

SELECT  p.text PostText,
        c.text CommentText
FROM
        (
            SELECT  id, text
            FROM    posts
            LIMIT   5
        ) p
        LEFT JOIN comments c
            ON c.postId  = p.id;

Upvotes: 7

Related Questions