2012-03-29 143 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