如何按mysql中另一个表的行数排序

时间:2013-12-20 19:20:07

标签: php mysql sql

我有这两个表,我想按第二个表的行数排序...我想要一个查询来显示 postid count()每个postid的评论...我上面的查询工作正常,但我想添加查询和表格帖子只需要帖子表选择* ...用于其他工作...但它必须在同一个查询...我的问题是当我添加和post表到上面的查询它将 count()乘以8,即在posts表中有多少个字段...它可以完成他的工作并且喜欢这样但是我不知道它是否正确,或者可能有更多更简单或更正确的方式!提前谢谢!

       comments                          posts
+---------+------------+       +---------+-----------------+
|  Name   |   Type     |       |  Name   |   Type          |
+---------+------------+       +---------+-----------------+
| id      |int(10) prim|  +----| postid  |  int(10) prim   |
| name    |varchar(128)|  |    | title   |  varchar(100)   |
| email   |varchar(255)|  |    | image   |  varchar(150)   |
| body    |   text     |  |    | video   |  varchar(200)   |
| postid  |   int(10)  |--+    | body    |     text        |
| dt      | timestamp  |       | author  |  varchar(50)    |
+---------+------------+       | postdate|   timestamp     |
                               | category|enum('1','2','3')| 
                               +---------+-----------------+



    <?php       
    $sql = "SELECT comments.postid, count(*) FROM comments GROUP BY comments.postid ORDER BY count(*) DESC LIMIT 3";
    $query = mysqli_query($db_conx, $sql);
    ?>

    Output of that query:   
    +--------+----------+ 
    | postid | count(*) |      
    +--------+----------+
    | 14     | 6        |
    | 13     | 4        | 
    | 15     | 3        | 
    +--------+----------+ 



    <?php       
    $sql = "SELECT comments.postid, count(*) FROM posts, comments GROUP BY comments.postid ORDER BY count(*) DESC LIMIT 3";
    $query = mysqli_query($db_conx, $sql);
    ?>

    Output of that query:   
    +--------+----------+ 
    | postid | count(*) |      
    +--------+----------+
    | 14     | 48       |
    | 13     | 32       | 
    | 15     | 24       | 
    +--------+----------+ 

0 个答案:

没有答案