简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM