1

最近、ブログ システムに取り組んでいるときに、問題が発生しました。1 つはブログ投稿用、もう 1 つはそれらの投稿へのコメント用です。これは、すべての投稿情報とコメント数を取得するために現在使用しているクエリです。

SELECT bp.*, COUNT(bpc.id) AS post_comments
FROM blog_posts AS bp
LEFT JOIN blog_post_comments AS bpc ON bpc.post_id = bp.id
LIMIT 0, 10

さて、タイトルで述べたように、10 件の投稿が返されるはずですが、これは 1 件の投稿に関するデータしか返しません。これはなぜですか?

ありがとう!

4

3 に答える 3

4

You are missing the GROUP BY clause, and since MySQL is lenient about aggregate functions and columns in the SELECT not appearing in the group by, it collapses down to one row showing the total count, but mixed column values from other columns.

SELECT bp.*, COUNT(bpc.id) AS post_comments
FROM blog_posts AS bp
LEFT JOIN blog_post_comments AS bpc ON bpc.post_id = bp.id
GROUP BY bp.id
LIMIT 0, 10

The more portable way to do this for RDBMS other than MySQL would be to join against a subquery that returns only the post_id and the number of posts per id, allowing the rest of the columns from blog_posts to be selected without appearing in the GROUP BY.

SELECT
  bp.*,
  bcount.counts
FROM 
  blog_posts AS bp
  LEFT JOIN (
     SELECT post_id, COUNT(*) AS counts 
     FROM blog_post_comments 
     GROUP BY post_id
  ) bcounts ON bp.id = bcounts.post_id
于 2012-07-15T18:55:45.037 に答える
2

Since you use COUNT, it will consider all posts as the same. Try this to see if it works:

SELECT bp.*, COUNT(bpc.id) AS post_comments
FROM blog_posts AS bp
LEFT JOIN blog_post_comments AS bpc ON bpc.post_id = bp.id 
GROUP BY bp.id
LIMIT 0, 10

I'm not sure if that's the problem. Just guessing. :)

于 2012-07-15T18:55:46.583 に答える
1

You get one record because COUNT() is an aggregate function. You should add a GROUP BY clause and COUNT() will work as you wanted.

于 2012-07-15T18:55:36.690 に答える