复杂的条件SQL语句

时间:2012-03-29 21:06:41

标签: php mysql sql

我有以下3个表格:

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)不属于但他或她的朋友所属的所有团队成员。我知道这听起来很混乱,但基本上,让我说我的名字是吉姆,我是丽莎和帕特里克的朋友。我想选择团队名称,团队ID以及Lisa和Patrick已经注册的每个团队的所有成员,并且我不属于那些团队。如果有一个团队,例如Patrick和我都是其成员,那么该团队不应该被退回。

过去一天我一直在努力解决这个问题,我们将非常感谢任何帮助。谢谢。另外,不包括foreign_keys的道歉......

1 个答案:

答案 0 :(得分: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)