从另一个表计数行

时间:2016-01-30 21:14:27

标签: php mysql count row

我有这个表结构

sites
id | name  | etc
1  | test  | etc
2  | test2 | etc
3  | test3 | etc

comments
id | site_id | comment
1  |    2    |   test comment
2  |    3    |   test2 comment
3  |    2    |   test3 comment

我想要选择列出所有网站 例如

test2
this is a test description
this is a test link
comments NR (2)

test3
this is a test description
this is a test link
comments NR (1)

我有这段代码来显示网站。 谁能告诉我如何计算评论表的行数?

$subcat_id = $_GET["id"];


        $stmt = $handler->prepare("SELECT *
                                    FROM sites sites
                                    LEFT JOIN comments comments ON ( sites.id = comments.site_id )
                                    WHERE sites.subcat_id = '$subcat_id' AND sites.status = 1
                                    GROUP BY sites.id
                                    ORDER BY RAND()");
        $stmt->execute();
        $no=$stmt->rowCount(); 
        while($row = $stmt->fetch(PDO::FETCH_OBJ)){
            $sites[]=$row;
        }

        $smarty->assign('site',$sites);
        $smarty->assign('anzahl',$no);

        $smarty->display('subcat.tpl');

1 个答案:

答案 0 :(得分:0)

稍微改写你的sql:

SELECT *
FROM sites sites
LEFT JOIN comments comments ON ( sites.id = comments.site_id )
WHERE sites.subcat_id = '$subcat_id' AND sites.status = 1
ORDER BY sites.id

现在您知道每个网站都会有连续的评论,如果有新网站要打印标题,您可以在php中查看。