从两个表中选择并计算发布的评论数

时间:2016-03-30 13:29:59

标签: php mysql

我正在尝试进行查询,该查询会向我显示帖子以及发布此帖子的评论数量。这是查询,但我有空白页

$result = $pdo->query("
    SELECT posts.*, comments.count(*)
    FROM posts
    LEFT JOIN comments ON posts.post_id = comments.post_id
    WHERE ( comments.post_id
          IN ( 
                SELECT MAX( post_id ) 
                FROM comments
                GROUP BY post_id
          )
    )
    OR ( 
          NOT EXISTS 
          (
                SELECT NULL 
                FROM comments
                WHERE comments.post_id = posts.post_id
          )
    )
    AND posts.post_id = :post_id
"); 

if ($result->execute(array(':post_id'=>$_GET['post_id'])))
{
      // rest of the code
}

我甚至不确定查询是否正确构造。目标是显示帖子和计数评论数量。喜欢 This post have 3 comments

当我执行此代码时,出现以下错误:

  

致命错误:在非对象

上调用成员函数execute()

发生在这一行:

if ($result->execute(array(':post_id'=>$_GET['post_id'])))

更新:最终和工作表单

SELECT posts . * , COUNT( comments.comment_id ) AS total
FROM posts, comments
WHERE  posts.post_id = comments.post_id
AND posts.post_id=:post_id

1 个答案:

答案 0 :(得分:1)

尝试查询

SELECT posts.*,COUNT(comments.`post_id`) AS totalcomment
FROM posts
LEFT JOIN comments   ON posts.post_id = comments.post_id