dqypcghd381390 2015-07-13 07:01
浏览 62
已采纳

显示帖子数量的类别

I'm making a blog. I have 2 tables, one for posts and the other for categories.

I want to display the category name, category date and the number of posts in each category. I have problems to display the number of posts in each category. In posts table I have a column called cat_id which is equal to category.id

I have these 2 MySQL queries:

mysql_query("select Count(posts.id) as NumberOfPosts, cat_id from posts group by cat_id");  

And

mysql_query("select name, date from categories");

I don't know how to have combine these two queries into one query. I'm using PHP.

  • 写回答

1条回答 默认 最新

  • dongxixian7803 2015-07-13 07:05
    关注

    You could use a join:

    SELECT name, date, NumberOfPosts
    FROM   categories c
    JOIN   (SELECT   cat_id, COUNT(*) AS NumberOfPosts
            FROM     posts
            GROUP BY cat_id) p ON c.id = p.cat_id
    

    EDIT:
    To include categories with no posts, you could use a left join instead of regular join. You just need to handle the nulls you'd get for NumberOfPosts, e.g., by using coalesce:

    SELECT      name, date, COALESCE(NumberOfPosts, 0) AS NumberOfPosts
    FROM        categories c
    LEFT JOIN   (SELECT   cat_id, COUNT(*) AS NumberOfPosts
                 FROM     posts
                 GROUP BY cat_id) p ON c.id = p.cat_id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答