简体   繁体   English

计算另一个表中的行

[英]Count Row from another table

I have this table structure 我有这个表结构

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

I want make a Select to list all sites eg. 我想选择以列出所有网站,例如。

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)

I have this code to display the sites. 我有这段代码来显示站点。 Can anybody tell me how i can count the rows of the comment 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');

Rewrite your sql slightly: 稍微重写一下你的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

Now you know you will have consecutive comments for each site and you can check in php if there is a new site for which you should print out a header. 现在您知道每个站点都有连续的注释,并且可以在php中检查是否有新站点需要打印标题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM