开发者

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

开发者 https://www.devze.com 2023-02-04 14:36 出处:网络
I\'m having a hard time coming up with exactly how to phrase this question so I\'ll give you an example.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消