2013-10-21 4 views
1

mysql을 사용하고 있으며 거의 ​​완벽하게 작동하는 쿼리가 있습니다.쿼리의 첫 번째 행에서 잘못된 결과 얻기

  • article_id를

코멘트

    0 : 나는 다음과 같은 세 개의 테이블이

보기

  • VIEW_ID
  • article_id를을 article_id를 comment_id

그리고이 모든 정보를 하나의 쿼리에 넣고 싶습니다. 나는 얼마나 많은 의견과 각 기사의 의견을보고 싶다. 오늘 나는 위대한 사람들의 도움을 받아 하나를 만들었지 만, 나는 다시 붙어 있습니다.

SELECT article.id_article, 
     COUNT(view.id_article), 
     COUNT(comment.id_article) 
FROM article LEFT JOIN view ON article.id_article = view.id_article 
      LEFT JOIN comment ON article.id_article = comment.id_article 
GROUP BY id_article 
ORDER BY id_article 

첫 번째 행에서만 잘못된 결과가 표시됩니다. 4 개의 댓글과 3 개의보기 대신에, 나는 둘 모두에서 24를 보았고 나머지는 괜찮기 때문에 이유를 알지 못합니다. 댓글 수가 4 등분되고 댓글과보기의 첫 번째 행에 재현 된 것처럼 보입니다.

답변

1

당신은 당신의 참여와 카티 제품 얻고있다 :

확실하지 (12)는 왜 24을 받고 =

1 조 * 4 개보기 * 3 개 의견을, 아마 당신은 동일한 ID를위한 2 개 개의 기사가 첫 번째 행 이상 반응의

SELECT article.id_article, 
      v.n_views, 
      c.n_comments 
    FROM article 
LEFT JOIN (SELECT article_id, 
        count(*) n_views 
      FROM view 
     GROUP BY article_id) v ON article.id_article = v.id_article 
LEFT JOIN (SELECT article_id, 
        count(*) n_comments 
      FROM comment 
     GROUP BY article_id) c ON article.id_article = c.id_article 
    GROUP BY id_article 
    ORDER BY id_article 
+0

동일로 : 내가 DISTINCT 사용할 수 없습니다 그렇지 않으면 나는 단지 모든 결과에 대해 1을 얻을 것이다 ... 그리고 나는 모든 원하는

SELECT article.id_article, COUNT(distinct view.id_view), COUNT(distinct comment.id_comment) FROM article LEFT JOIN view ON article.id_article = view.id_article LEFT JOIN comment ON article.id_article = comment.id_article GROUP BY id_article ORDER BY id_article 

이 쿼리를 작성하는 또 다른 방법이 될 수 있습니다) – Th3lmuu90

+0

다른 버전을보십시오 :) – mucio

+0

완벽하게 작동합니다! 감사! 그건 좋은 긴 쿼리 hehehe – Th3lmuu90