2011-05-04 4 views
0

다음 쿼리에 이상한 문제가 있습니다. 정확히 일치합니다. 카운트 부분이 주어진 'hintout' 내가 선택 부분에 다음을 추가하려고여러 테이블에서 선택 개수로 이상한 문제가 발생했습니다 (조인 포함)

SELECT h.* 
    , h.permalink AS hintout_permalink 
    , hi.hinter_name 
    , hi.permalink 
    , hf.user_id AS followed_hid 
    , ci.city_id, ci.city_name, co.country_id, co.country_name, ht.thank_id 
    , COUNT(hc.comment_id) AS commentsCount 
FROM hintouts AS h 
INNER JOIN hinter_follows AS hf ON h.hinter_id = hf.hinter_id 
INNER JOIN hinters AS hi ON h.hinter_id = hi.hinter_id 
LEFT JOIN cities AS ci ON h.city_id = ci.city_id 
LEFT JOIN countries as co ON h.country_id = co.country_id 
LEFT JOIN hintout_thanks AS ht ON (h.hintout_id = ht.hintout_id 
    AND ht.thanker_user_id = 1) 
LEFT JOIN hintout_comments AS hc ON hc.hintout_id = h.hintout_id 
WHERE hf.user_id = 1 
GROUP BY h.hintout_id 

: 나는 각 hintout에 대한 '투표'의 수를 가져옵니다 비슷한 수를 추가하기 위해 노력하고있어

, 아래의 쿼리입니다

COUNT(ht2.thanks_id) AS thanksCount 

과에 다음과 같은 조인 :

LEFT JOIN hintout_thanks AS ht2 ON h.hintout_id = ht2.hintout_id 

하지만 이상한 일이 일어나고, 내가 어떤 답변이나 해결책을 찾을 수 없습니다하는, 내가이 addtiional 부분을 추가하는 순간이 의견에 대한 카운트가 파괴 얻을 것입니다 (나는 이상하고 이상한 숫자를 얻는다.) 그리고 나는 같은 숫자의 감사를 얻는다. - 왜 또는 어떻게 고칠 수 있는지 이해할 수 없었다. 그리고 중첩 된 쿼리를 사용하지 않을 것이다.

그래서 어떤 도움이나 포인터가 크게 감사하겠습니다!

추신 :이 두 번 게시되었을 수 있습니다,하지만 당신은

LEFT JOIN hintout_thanks AS ht2 ON h.hintout_id = ht2.hintout_id 

행 증가의 수를 추가 할 때 나는 이전 게시물

답변

2

을 찾을 수 없습니다, 당신은 중복 행을 얻을 테이블 hcCOUNT(hc.comment_id)에 두 번 집계됩니다. 당신은 ID 만 계산 독특한 모습에

COUNT(hc.comment_id) <<-- counts duplicated 
/*with*/ 
COUNT(DISTINCT(hc.comment_id)) <<-- only counts unique ids 

을 대체 할 수 있습니다.

고유하지 않은 값의 경우 co.county_name과 같이 count(distinct은 별개 국가 만 표시되므로 (결과가 모두 미국 인 경우 개수는 1이되므로) 작동하지 않습니다. Quassnoi

은 하위 선택의 수를 바꾸어 전체 카운트 문제를 해결 가질 수 있도록 모든 사람들에 의한 별도의 행 그 계산에 영향을주지 않습니다 합류했다.

+0

아하, 은 하위 아이디어를 선택하거나 조인 또는 별개를 사용하여 방법을 찾는 것이 더 좋습니까? 아니면 다른 방법이 있는지 모르겠습니까? –

+1

@roy naufal, 둘 다 자리를 잡고 있습니다. 나는 항상'join' +'distinct '경로를 먼저 찾는다. 너무 느리다면 나는 sub-select를 시도하고 더 빠르다는 것을 알 수있다. 코드를 완성하고 테스트하여 더 나은 코드가 무엇인지 확인해야합니다. – Johan

1
SELECT h.*, h.permalink AS hintout_permalink, hi.hinter_name, 
     hi.permalink, hf.user_id AS followed_hid, 
     ci.city_id, ci.city_name, co.country_id, co.country_name, 
     ht.thank_id, 
     COALESCE(
     (
     SELECT COUNT(*) 
     FROM hintout_comments hci 
     WHERE hc.hintout_id = h.hintout_id 
     ), 0) AS commentsCount, 
     COALESCE(
     (
     SELECT COUNT(*) 
     FROM hintout_comments hti 
     WHERE hti.hintout_id = h.hintout_id 
     ), 0) AS thanksCount 
FROM hintouts AS h 
JOIN hinter_follows AS hf 
ON  hf.hinter_id = h.hinter_id 
JOIN hinters AS hi 
ON  hi.hinter_id = h.hinter_id 
LEFT JOIN 
     cities AS ci 
ON  ci.city_id = h.city_id 
LEFT JOIN 
     countries as co 
ON  co.country_id = h.country_id 
LEFT JOIN 
     hintout_thanks AS ht 
ON  ht.hintout_id = h.hintout_id 
     AND ht.thanker_user_id=1 
WHERE hf.user_id = 1 
관련 문제