我创建了一个表来放置每篇文章的注释,因此comment_id
是计数注释的自动增量,而article_id
是来自另一个表(外键)的文章ID。
我想计算每篇文章的评论数量并将其放入新记录或其他内容中 所以我可以在文章页面中显示它:“评论数量:5”
答案 0 :(得分:3)
select article_id, count(article_id) as comment_count
from comments
group by article_id
order by article_id
答案 1 :(得分:2)
您可以将COUNT
和GROUP BY
用于此
尝试:
SELECT COUNT(*) as num_comments, article_id
FROM comment_table
GROUP BY article_id
答案 2 :(得分:1)
我只是从头脑中做到这一点,所以不确定它是否会起作用:
// once you have connected to the database:
$query = "SELECT COUNT(article_id) FROM table_name WHERE article_id=1";
// you might want to have a variable set so that the article_id isn't hardcoded
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "the number of comments: ". $row['COUNT(article_id)'] ."
}