2013-05-18 2 views
1

나는 그가 팔로우 한 총 팔로어 수와 함께 그가 생성했거나 팔로우하는 사용자의 그룹을 얻으 려하고 가장 최근의 팔로워 날짜를 얻고 싶습니다. 그래서 주문할 수 있습니다. 그것으로. 나는 두 테이블 그룹그룹 회원 수를 선택하고 같은 쿼리에서 상태를 따르는 방법 mysql

id title creator_id created 
4 test3 123   1224322344 
5 test2 213   2342344444 

가 따라가 내가이 쿼리

SELECT g. * , IFNULL(f.total_followers, 0) total_followers 
FROM groups AS g 
LEFT JOIN (

    SELECT to_id, COUNT(*) AS total_followers 
    FROM follow 
    WHERE is_group =1 
    GROUP BY to_id 
) AS f ON (g.id = f.to_id) 
where g.creator=123 
GROUP BY g.id 
g.created DESC 
LIMIT 10 

그러나 그것은 단지 나에게 사용자 자신의 그룹의 추종자의 수를 반환을 시도

id to_id follower_id is_group created 
1 4  222    1  234324324 
1 4  123    1  444234234 
1 5  213    1  234234444 

그가 따르는 그룹이 아닙니다.

도움이 될 것입니다. IN 사용하지 않고

감사

답변

1
SELECT g.* , IFNULL(f.total_followers, 0) total_followers, f.most_recent 
FROM groups AS g 
LEFT JOIN (
    SELECT to_id, COUNT(*) AS total_followers, MAX(created) AS most_recent 
    FROM follow 
    WHERE is_group =1 
    GROUP BY to_id 
) AS f ON (g.id = f.to_id) 
WHERE g.creator=123 
OR g.id in (SELECT to_id FROM follow WHERE follower_id = 123) 
ORDER BY most_recent DESC 
LIMIT 10 

:.

SELECT g.* , IFNULL(f.total_followers, 0) total_followers, f.most_recent 
FROM (SELECT * FROM groups where creator = 123 
     UNION DISTINCT 
     SELECT g.* FROM groups AS g1 
     JOIN follow AS f1 ON (g1.id = f1.to_id) 
     WHERE f1.follower_id = 123) AS g 
LEFT JOIN (
    SELECT to_id, COUNT(*) AS total_followers, MAX(created) AS most_recent 
    FROM follow 
    WHERE is_group =1 
    GROUP BY to_id 
) AS f ON (g.id = f.to_id) 
ORDER BY most_recent DESC 
LIMIT 10 
+0

이 작품은, 정말 감사합니다 :) 일반적으로 –

+0

는 "에 (이하"절은 성능 개 – Drew

+0

I 미입니다 결코 이 빠른 방법이 있으면 감사 할 것입니다. 절에서 사용하는 것 외에 다른 방법으로 할 수 있습니까? –

관련 문제