开发者

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_comment开发者_运维知识库s.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:

  • http://dev.mysql.com/doc/refman/5.5/en/join.html
  • http://www.w3schools.com/SQl/sql_join_inner.asp

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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜