从另一个 table 计数行

Count Row from another table

我有这个table结构

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

我想制作一个 Select 来列出所有网站 例如

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)

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

$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');

稍微重写你的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

现在您知道每个网站都会有连续的评论,如果有新网站您应该打印出 header。

,您可以签入 php