2012-03-29 142 views
1

我有以下3个表:复杂,有条件的SQL语句

team_data

id 
team_id 
team_name 

team_members

userid 
teamid 

用户

uid 
name_f 
name_l 

朋友

friend_id 
friend_one 
friend_two 

当我运行一个查询,选择登录用户的球队,我运行以下命令,它完美的作品:

SELECT t.team_id, 
     t.team_name 
FROM team_data t, 
     team_members m 
WHERE t.team_id = m.teamid 
     AND m.userid = $session_id 
ORDER BY t.team_id DESC 

当我运行一个查询选择所有登录用户的朋友,我运行以下,它也可以很好地工作:

SELECT a.name_f, 
     a.uid, 
     a.name_l, 
FROM users a, 
     friends b 
WHERE a.uid = b.friend_two 
     AND b.friend_one = $session_id 
ORDER BY b.friend_id DESC 

现在,棘手的部分来了。我期望选择team_id和team_name以及用户($ session_id)不属于但他或她的朋友所属的所有团队成员。我知道这听起来很混乱,但基本上,让我们说我的名字是吉姆,我是Lisa和Patrick的朋友。我想选择球队名称,球队ID以及Lisa和Patrick签约的每个球队的所有成员,并且我不属于这些球队。例如,如果有一个团队,帕特里克和我都是成员,那么该团队不应该退回。

我一直在努力与这一过去的一天,任何帮助将不胜感激。谢谢。此外,道歉不包括foreign_keys ...

回答

2
select distinct 
    tm.*, /* The teams */ 
    tma.* /* The members of those teams */ 
from 
    friends f /* My friends */ 
    inner join team_members tm on tm.userid = f.friend_two /* Teams of my friends */ 
    inner join team_data td on td.teamid = tm.teamid /* Team data of those teams */ 
    /* You'll need to join team_member again to get all members of these teams */ 
    inner join team_members tma on tma.teamid = tm.teamid /* Members of those teams. */ 
where 
    f.friend_one = $session_id and 
    /* Exclude those teams that I'm already member of */ 
    not exists (
    select 
     'x' /* Constant value might speed up thing marginally */ 
    from 
     team_members tmm 
    where 
     tmm.teamid = tm.teamid and 
     tmm.userid = f.friend_one) 
+0

哦,甜蜜的耶稣,它的作品!对此我们不能够感谢你。 – user1011713 2012-03-29 21:30:19