[英]Selecting and matching data from 3 tables
SCENARIO 场景
x3 tables: x3表格:
Members
member_id | member_name
-------------
1 | member 1
2 | member 2
3 | member 3
teams
team_id | team_name
-------------
1 | team 1
2 | team 2
3 | team 3
team_members
team_member_id | member_id | team_id
------------------------------------
1 | 1 | 1
2 | 2 | 2
3 | 3 | 3
Members can be associated with more than one team so that is why I separated the data out into 3 tables. 成员可以与多个团队相关联,这就是为什么我将数据分成3个表的原因。
I want to list out all the teams, and underneath them show the members of each of those teams. 我想列出所有团队,并在其下方显示每个团队的成员。 I am not sure what the best approach is on this one as I am new to database design. 我不确定这是最好的方法,因为我是数据库设计的新手。
Currently all I am doing is outputting the two values: 当前我正在做的是输出两个值:
<?php
$sql = "SELECT * FROM team_members";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo 'teamID: <strong>' . $row["team_id"] . '</strong><br>';
echo 'memberID: <strong>' . $row["member_id"] . '</strong><br>';
}
}
?>
You will have to JOIN
between those tables like below, performing an inner join
which will give only matching records. 您将必须在如下所示的这些表之间进行JOIN
,执行inner join
JOIN
,该JOIN
只会给出匹配的记录。 In case you want all teams irrespective of whether those teams have any member or not then consider doing a left join
instead. 如果您希望所有团队不管这些团队是否有成员,请考虑进行left join
。
select t.team_id, m.member_ID, m.member_name
from teams t
left join team_mambers tm on t.team_id = tm.team_id
left join members m on m.member_ID = tm.member_ID;
Explanations: 说明:
Since you have a many to many relationship between teams and members; 由于团队和成员之间存在多对多关系; you have a relationship table where you maintain the relationship (OR Foreign keys of the tables) in a different table team_mambers
. 您有一个关系表,可以在另一个表team_mambers
维护关系(表的外键)。 Thus for you to join
teams
with members
; 因此,您可以与members
一起join
teams
; you will first have to join with the relationship table and then join with the other table members
based on the matched id's. 您将首先必须与关系表联接,然后根据匹配的ID与其他表members
联接。
I have perform a outer join
keeping in mind that not all teams may have members in it and thus outer join will get you all the teams irrespective of members in it or not. 我执行outer join
要记住,并不是所有团队中都可能有成员,因此外部联接将使您所有团队都受到关注,无论成员是否参与。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.