2013-11-26 157 views
0

我有這樣的團隊表(可以是一個項目表以及)和成員表獲得團隊成員在一個特定的團隊在MySQL

+-----------+--------------+------+-----+---------+----------------+ 
| Field  | Type   | Null | Key | Default | Extra   | 
+-----------+--------------+------+-----+---------+----------------+ 
| id  | int(11)  | NO | PRI | NULL | auto_increment | 
| team_name | varchar(100) | NO | UNI | NULL |    | 
| team_desc | varchar(200) | NO |  | NULL |    | 
| createdby | varchar(100) | NO |  | NULL |    | 
+-----------+--------------+------+-----+---------+----------------+ 

和成員表

+-------------+--------------+------+-----+---------+----------------+ 
| Field  | Type   | Null | Key | Default | Extra   | 
+-------------+--------------+------+-----+---------+----------------+ 
| id   | int(11)  | NO | PRI | NULL | auto_increment | 
| firstname | varchar(45) | NO |  | NULL |    | 
| lastname | varchar(45) | NO |  | NULL |    | 
| address  | varchar(200) | NO |  | NULL |    | 
| city  | varchar(45) | NO |  | NULL |    | 
| state  | varchar(45) | NO |  | NULL |    | 
| country  | varchar(45) | NO |  | NULL |    | 
| email  | varchar(45) | NO |  | NULL |    | 
| phone  | varchar(10) | YES |  | NULL |    | 
| experience | varchar(45) | NO |  | NULL |    | 
| designation | varchar(45) | NO |  | NULL |    | 
| username | varchar(45) | NO |  | NULL |    | 
| password | varchar(45) | NO |  | NULL |    | 
+-------------+--------------+------+-----+---------+----------------+ 

和這兩個表加入了這個teams_members表,

+------------------+---------+------+-----+---------+----------------+ 
| Field   | Type | Null | Key | Default | Extra   | 
+------------------+---------+------+-----+---------+----------------+ 
| teams_members_id | int(11) | NO | PRI | NULL | auto_increment | 
| teams_id   | int(11) | NO | MUL | NULL |    | 
| members_id  | int(11) | NO | MUL | NULL |    | 
+------------------+---------+------+-----+---------+----------------+ 

我想要做的是讓一個特定的團隊成員。我很困惑,我怎麼會做這個(可能是我啞然:P)

SELECT * 
FROM teams_members tm, members m, teams t 
WHERE tm.members_member_id = m.id 
AND t.team_name='team name can be anything' 
AND tm.id = t.id 

它返回0的結果。我可能在哪裏錯了?

回答

2

查詢中的join with teams_member and team不正確

試試這個:

SELECT * 
FROM teams_members tm, members m, teams t 
WHERE tm.members_member_id = m.id 
AND t.team_name='team name can be anything' 
AND tm.teams_id = t.id 

OR

SELECT * 
FROM teams_members tm 
inner join members m on tm.member_id=m.id 
inner join teams t on tm.teams_id=t.id 
WHERE 
t.team_name='team name can be anything' 
+0

我實際上正在考慮使用'INNER JOIN'。這個技巧謝謝你! – user1601973

0

如果你是開放使用嵌套查詢:

select * 
    from Members 
    where id in(
       select members_id 
       from team_members 
       where teams_id in(
            select id 
            from teams 
            where team_name='anything'))