获取关系表数据

时间:2017-02-22 12:08:25

标签: php mysqli

我有以下表格:

member
id, firstName, lastName

team
id, name

teamMember
id, teamId, memberId

我正在尝试访问关系表,因此我可以输出成员firstName和Lastname:

$sql = "SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId 
        FROM teamMember 
        JOIN member
        JOIN team
        ON teamMember.memberId = member.id
        WHERE dashboardId = 1 AND team.id = 1";

我在team.id中设置了一个硬值,所以我可以测试以确保它现在返回团队1的成员。

所以这里的最终目标是我需要访问关系表,以便返回与ID中选择查询中设置的团队ID相关联的成员名称。

我正在努力满足输出需求。

并返回如下值:

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "{$row['firstName']} {$row['lastName']}<br>";
    }
}

我看到的错误是:

Notice: Trying to get property of non-object in

其中指的是:if ($result->num_rows > 0) {

我想看到的输出是firstName表中的成员lastNamemember

1 个答案:

答案 0 :(得分:1)

您可能希望与所需团队ID相关联的所有结果或行。但是,使用INNER JOIN,您只能为一个团队获得一行,因为这就是JOIN的工作方式。

相反,你应该使用这样的查询:

SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId 
        FROM teamMember 
        JOIN member
        ON teamMember.memberId = member.id
        WHERE dashboardId = 1 AND teamMember.teamId = 1"

希望这会奏效。

但是,从bool(false)开始,您的查询也被破坏了,无法获得所需的结果。 在您的查询中,您已加入三个表并仅为一个表定义条件。这将是您的查询应该是什么样的

"SELECT member.id, member.firstName, member.lastName, team.id, teamMember.id, teamMember.memberId, teamMember.teamId 
        FROM teamMember 
        JOIN member
        ON teamMember.memberId = member.id
        JOIN team
        ON teamMember.teamId= team.id
        WHERE dashboardId = 1 AND team.id = 1";