douhui8163 2015-06-01 20:10
浏览 210

MySQL:如何返回表中的所有行,并从另一个表中计算具有匹配ID的行数

I'm a front-end developer by trade, please have mercy on my soul for the horrific PHP and SQL, I'm here to learn!

So, I have a couple of tables, let's call them "categories", and "posts"

My "category" table has these fields:

  • categoryID
  • categoryName
  • categoryDisplayName

My "posts" table has these fields:

  • postID
  • postTitle
  • postCategoryID
  • otherNoneImportantFields

I can output all my Categories very simply:

$getCategories = mysql_query("SELECT categoryID, name, displayName 
                              FROM jobCategories 
                              ORDER BY categoryID ASC");
$numberOfCategories = mysql_num_rows($getCategories);

Then I can do a while loop and output all the categories:

if ($numberOfCategories > 0) {
    while($row = mysql_fetch_array($getCategories)) {
        $categoryID = $row['categoryID'];
        $name = $row['name'];
        $displayName = $row['displayName'];

        echo "<li>" . $displayName . "</li>";
        // I'm using the other variables to create a link
    }
}

Now, to the question: I want a variable in the while loop that is a count of all the posts that has that categoryID. I'm unsure if I can do a subquery, or if I have to do a join to get that variable to output.

As a secondary question, is the PHP in question sane, or have a missed a much easier/cleaner way of doing what I'm doing?

Thanks in advance :)

  • 写回答

2条回答 默认 最新

  • doujiang1001 2015-06-01 20:21
    关注

    This will return your jobCategories table with an extra column postsCount equal to the number of posts matching the row's categoryID.

    SELECT categoryID, categoryName, categoryDisplayName, IFNULL(postsCounts.cnt, 0) AS postsCount
    FROM jobCategories
    LEFT JOIN (
      SELECT postCategoryID, count(*) as cnt
      FROM posts
      GROUP BY postCategoryID
    ) postCounts 
    ON postCounts.postCategoryID = jobCategories.categoryID
    
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)