计入多个连接

时间:2012-12-13 13:49:23

标签: mysql join

我需要获得不同的用户ID列表,这些列表已在匹配中进行了实时登记(checkins.ctype ='live')哪里也住了三(3)个或更多他的朋友

以下是数据库设计:

enter image description here

我成功检索了匹配列表,其中有超过3位用户进行了实时签到,但我需要知道他们是否是我的朋友。

我的代码现在直到:

SELECT DISTINCT
    f1.id
FROM 
    fanusers f1

JOIN    checkins c
ON c.fanuser_id = f1.id

WHERE
c.ctype = 'live'
AND
c.match_id IN (
                                SELECT
                                    c1.match_id
                                FROM
                                    checkins c1
                                WHERE
                                    c1.ctype = 'live'
                                GROUP BY
                                    c1.match_id
                                HAVING
                                    COUNT(*)> 3
                            )

...and he has 3 ore more than 3 friends lived checked-in in the same match (c.match_id)

任何Ideea? 感谢

1 个答案:

答案 0 :(得分:1)

如果在fanuser_id上加入checkins到fanuser_friends,然后进一步加入到friend_id上的签到,通过fanuser_id和match_id分组找到相关朋友的数量,然后将结果限制在朋友数量上?

SELECT DISTINCT c.fanuser_id
FROM checkins c 
INNER JOIN fanuser_friends f on 
f.fanuser_id = c.fanuser_id 
INNER JOIN checkins c2
on c2.fanuser_id = f.friend_id
AND c2.match_id = c.match_id
WHERE c.ctype = 'live'
AND c2.ctype = 'live'
GROUP BY c.fanuser_id, c.match_id
HAVING COUNT(*) >= 3;