2011-12-02 1 views
1

나는 해당 투표에 대한 의견 및 요약 통계를 선택하려고합니다. 모든 의견에 투표가있는 것은 아니며 투표지가 1 표 이상을 가질 수 있습니다. 여기 내 쿼리는 다음과 같습니다.간단한 MySQL 가입이 작동하지 않습니다.

select 
    `article-comments`.id, 
    `article-comments`.user as user_id, 
    concat(users.first_name, ' ', users.last_name) as name, 
    users.job_title, 
    users.company_name, 
    avatar, 
    `article-comments`.content, 
    datediff(now(), `article-comments`.date_added) as diff, 
    `article-comments`.date_added as date, 
    count(`comment-votes`.id) as votes_count, 
    sum(`comment-votes`.score) as votes_score 
from 
    `article-comments` left outer join `comment-votes` on `article-comments`.id = `comment-votes`.comment, 
    users 
where 
    `article-comments`.status = 1 
&& `article-comments`.article = $resource_id 
&& `article-comments`.user = users.id 
&& `comment-votes`.status = 1 
order by 
    `article-comments`.id asc 

이것은 조인없이 완벽하게 작동하지만 그걸로 1 행만 반환합니다.

아이디어가 있으십니까?

+1

당신이 완벽하게 작동 말한다는 가입없이 당신에게 원하는 결과를 얻을 수 있습니까? –

+0

문제를 격리시키기 위해 쿼리를 간소화하면 SELECT의 불필요한 열을 제거하고 WHERE 절의 값을 하드 코딩하는 것이 도움이됩니다. - $ table 및 $ resource_id는 무엇입니까? – mikel

+0

@Adam - 그렇습니다. 요약 통계량()과 sum()을 뺀 것입니다. – bcherny

답변

0

시도 :

select 
       `article-comments`.id, 
       `article-comments`.user as user_id, 
       concat(users.first_name, ' ', users.last_name) as name, 
       users.job_title, 
       users.company_name, 
       avatar, 
       `article-comments`.content, 
       datediff(now(), `article-comments`.date_added) as diff, 
       `article-comments`.date_added as date, 
       count(`comment-votes`.id) as votes_count, 
       sum(`comment-votes`.score) as votes_score 
      from 
       `article-comments` left join `comment-votes` on (`article-comments`.id = `comment-votes`.comment), 
       users 
      where 
       `article-comments`.status = 1 
      && `article-comments`.$table = $resource_id 
      && `article-comments`.user = users.id 
      order by 
       `article-comments`.id asc 
+0

고마워요,하지만 여전히 같은 행을 반환합니다 : [ – bcherny

+0

COUNT 및 SUM과 같은 집계 함수를 사용하면 표시되는 내용이 단일 행 항상. 해당 테이블의 행 수를 얻으려면 고전적인 "SELECT COUNT (*) FROM atable"을 고려하십시오. 이러한 함수와 함께 GROUP BY를 사용하여 필요한 데이터를 가져와야합니다. MySQL의 기본 동작은 누군가가 GROUP BY 문에 포함되지 않은 필드를 참조 할 수있게하여 일부 불확실한 결과를 초래합니다. 주제에 대한 자세한 내용은 http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html#sqlmode_only_full_group_by를 참조하십시오. – wisefish