I've got a query that currently queries a Post
table while LEFT JOINing a Comment
table. It fetches all Posts and their respective Comments. However, I want to limit the number of Comments returned. I tried adding a sub-select, but ran into errors if I didn't LIMIT the results to 1. I'm really not sure how to go about this while still using only one query. Is this possible?
相关问题
- SQL join to get the cartesian product of 2 columns
- sqlyog export query result as csv
- NOT DISTINCT query in mySQL
- MySQL: conduct a basic search
- Why sometimes there is one of more gap(s) in the v
This one should get your posts with the three most recent comments per post, assuming that your tables look like that:
post:
id
,post_text
comment:
id
,post_id
,comment_text
The sub-query is used to get recent comments first and to number them per post, while the outer select removes older comments.
You can't limit a join unless you have some convenient value to filter on (e.g.
where pos between 1 and 5
). You can select the first comment separately, the second comment, the third comment and so on, and union the results. Something ugly like: