简体   繁体   中英

Please help me write a mysql query

I need to find the news items from news table and the number of comments for each news item from comments table . I need this in a single array/resultset... the tables are linked by news.id=news_comments.news_id . Any help?

How about something like

SELECT  news.id,
        COUNT(comments.news_id) TotalComments
FROM    news LEFT JOIN
        comments    ON  news.id=news_comments.news_id
GROUP BY    news.id

If you use a left join, the result set will also return all news articles with no comments, where as if you use an inner join, these articles will be excluded from your result set.

It sounds like you should check out some tutorials, or buy a book on learning SQL:

The things you need to look into are how to take a count, and how to do an inner join. This is a fairly basic query, so you shouldn't have any problems once you work up to it.

If you get stuck on a particular part, let us know, show us what you've got so far, and maybe we can provide more specific help.

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