2015-01-11 4 views
0

그래서 나는 투표를 기반으로 가장 인기있는 게시물을 얻기 위해 사용하고 있는데이 글의 각 그들에게 링크가이 SQL 쿼리 ..SQL 쿼리는 레일에서 가장 인기있는 게시물을 얻을 수

I이 고유 한 링크가 있고 가장 높은 득표를 가진 게시물 만 얻고 싶습니다. 더 자세한 infomrations없이

ListsPost.find_by_sql("SELECT distinct lists_posts.*, 
      COALESCE(rs_reputations.value, 0) AS votes FROM \"lists_posts\" LEFT JOIN rs_reputations ON 
      lists_posts.id = rs_reputations.target_id AND rs_reputations.target_type = 'ListsPost' AND 
      rs_reputations.reputation_name = 'votes' AND rs_reputations.active = 't' ORDER BY votes desc, lists_posts.updated_at desc") 

답변

0

, 내가

SELECT lists_posts.*, rs_reputations.value 
    FROM \"lists_posts\" 
    LEFT JOIN rs_reputations 
    ON lists_posts.id = rs_reputations.target_id 
    AND rs_reputations.target_type = 'ListsPost' 
    AND rs_reputations.reputation_name = 'votes' 
    AND rs_reputations.active = 't' 
    AND rs_reputations.value IN ( SELECT MAX(COALESCE(rs_reputations.value, 0)) AS max_votes 
          FROM \"lists_posts\" 
          LEFT JOIN rs_reputations 
          ON lists_posts.id = rs_reputations.target_id 
          AND rs_reputations.target_type = 'ListsPost' 
          AND rs_reputations.reputation_name = 'votes' 
          AND rs_reputations.active = 't' 
         ) 

두 단계를이 쿼리를 작성, 그래서 최선의 희망 :

1) 하위 선택

한 최대 값을 발견 MAX(COALESCE(rs_reputations.value, 0)) 2)이 rs_reputations.value를 사용하여 모든 레코드에 대한 주 선택 검색 및 표시

테이블 구조에 대한 자세한 정보가 있으면, 내 쿼리를 최적화 할 수 있습니다.

+0

거의 작동하는 것처럼 보입니다. 문제는, 각 lists_posts는 그 안에 게시물이 있습니다. 나는 같은 게시물을 가진 lists_posts를 찾고 싶지만, 가장 높은 투표를 가진 사람 만 반환하고 싶습니다. –

0

많은 시행 착오 끝에 처음부터 시작하기로 결심했습니다. 그것은 일하는 것처럼 보이지만 조금 정제하면됩니다.

SELECT lp.*, COALESCE(rs_reputations.value, 0) as votes 
FROM lists_posts AS lp 
INNER JOIN(
    SELECT lists_posts.post_id, lists_posts.id, MAX(rs_reputations.value) 
    FROM lists_posts 
    LEFT JOIN rs_reputations 
    ON lists_posts.id = rs_reputations.target_id 
    GROUP BY lists_posts.post_id)l 
ON lp.post_id = l.post_id 
AND lp.id = l.id 
LEFT JOIN rs_reputations ON 
    lp.id = rs_reputations.target_id 
AND rs_reputations.target_type = 'ListsPost' 
AND rs_reputations.reputation_name = 'votes' 
AND rs_reputations.active = 't' 
ORDER BY votes desc, updated_at desc 
관련 문제