如何将具有多个公共字段的两个表连接到搜索过滤器

时间:2016-04-02 03:12:02

标签: php mysql sql

我有2个表bpi_registration和bpi_teamProfile。 bpi_registration中的字段为:id, id_school, first_name,last_name,email,city,state,country,bpi_teamProfile表中的字段为id_team, team_name, id_student1, id_student2, id_student3现在为id_student1,id_student2,id_student3包含bpi_registration中相同的id个学生。我不知道如何连接多个字段。我写的查询如下。如果我错了,请纠正我:

SELECT * FROM bpi_registration
            INNER JOIN bpi_teamProfile
            ON bpi_registration.id=bpi_teamProfile.id_student1
            AND bpi_registration.id=bpi_teamProfile.id_student2
            AND bpi_registration.id=bpi_teamProfile.id_student3
            AND bpi_registration.id=bpi_teamProfile.id_student4
            AND bpi_registration.id=bpi_teamProfile.id_student5

我正在尝试实施搜索过滤器,以便当有人点击“团队”下拉列表时,firstname,lastname,email,city,state,country中的bpi_registration会显示出来。下面是我的PHP代码

if (isset($_GET['Team']))
{

    		
    		
    $sql="SELECT * FROM bpi_registration
            INNER JOIN bpi_teamProfile
            ON bpi_registration.id=bpi_teamProfile.id_student1
            AND bpi_registration.id=bpi_teamProfile.id_student2
            AND bpi_registration.id=bpi_teamProfile.id_student3
            AND bpi_registration.id=bpi_teamProfile.id_student4
            AND bpi_registration.id=bpi_teamProfile.id_student5"
            
    $userQuery = "{$sql} WHERE bpi_teamProfile.team_name = :team_id";
    $user = $db->prepare($userQuery);
    $user->execute(['team_id' => $_GET['Team']]);
    $selectedUser=$user->fetch(PDO::FETCH_ASSOC);
	

    if(isset($selectedUser))
    {
        echo '<tr>';
        echo '<td>' . $selectedUser['first_name'] . '</td>';
        echo '<td>' . $selectedUser['last_name'] . '</td>';
        echo '<td>' . $selectedUser['email'] . '</td>';
        echo '<td>' . $selectedUser['address_city'] . '</td>'; 
        echo '<td>' . $selectedUser['address_state'] . '</td>'; 
        echo '<td>' . $selectedUser['address_country'] . '</td>';
    echo '</tr>';
    }
}

当我们点击团队过滤器时,网址会显示为https://www.example.com/retrieve1.php?Grade=&School=&Team=mary+winners&Students=

然而,我无法获得理想的结果。

1 个答案:

答案 0 :(得分:2)

学生似乎不太可能将给定行中的列 all 映射回相同的id(在注册中)...或者查询将正确返回。如果它们不同,是否要加入“或”?

SELECT * FROM bpi_registration
            INNER JOIN bpi_teamProfile
            ON (bpi_registration.id=bpi_teamProfile.id_student1)
            OR (bpi_registration.id=bpi_teamProfile.id_student2)
            OR (bpi_registration.id=bpi_teamProfile.id_student3)
            OR (bpi_registration.id=bpi_teamProfile.id_student4)
            OR (bpi_registration.id=bpi_teamProfile.id_student5)