简体   繁体   中英

Best mysql query for selecting multiple rows that EACH need multiple associative rows from another table

I'm having a hard time coming up with exactly how to phrase this question so I'll give you an example.

Let's say a user requests a page that is going to show multiple articles AND multiple comments for EACH one of those articles. So not only do you need to select multiple records of articles but each one of those records is going to need to have several comment records associated with it.

What is the most optimal query to accomplish this? Thanks.

This is no absolute right or wrong, join will return larger set of data but can get everything in one query

Depend on your requirement, if you just need the comment count + list of comments ID (for later usage), consider to use group_concat

select 
  article.*, 
  group_concat(comment.id) as comments, 
  count(comment.id) as comments_count
from 
  article
left join comment 
on comment.article_id=article_id
group by article.id;

the columns comments will contains all the comments id, and the comments_count return number of comments for each article

PS : I think left join is more appropriate

You want to use an INNER JOIN.

SELECT 
     article.*,
     comment.*
FROM
     article
INNER JOIN
     comment
ON
     comment.article_id = article.id

This will give you redundant data (same article data for multiple rows) but only one sql statement / connection to the db.

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