如何使用另一个表中的ID显示一个表中的属性

时间:2017-11-28 21:49:25

标签: php sql oracle select

我在Oracle数据库中有以下表格:

CREATE TABLE Team
 (
  teamID INT NOT NULL,
  teamName VARCHAR(50),
  wins INT,
  losses INT,
  otlosses INT,
  points INT,
  PRIMARY KEY (teamID)
);


    CREATE TABLE Matchup
       (
           matchID INT NOT NULL,
           roundID INT NOT NULL,
            team1ID INT NOT NULL,
            team2ID INT NOT NULL,
            PRIMARY KEY (matchID),
            FOREIGN KEY (roundID) REFERENCES Round (roundID),
            FOREIGN KEY (team1ID) REFERENCES Team (teamID),
            FOREIGN KEY (team2ID) REFERENCES Team (teamID) 
         );

我正在循环比赛表并显示所有比赛。我只能让它显示TeamID,并且我试图让它使用我从Matchup表中获得的ID来显示Team表中的teamName。

这是我到目前为止所尝试的但似乎无法让它发挥作用。

 $query = 'SELECT team1ID, team2ID  FROM Matchup WHERE RoundID=1 IN (SELECT teamName FROM Team WHERE team1ID=teamID AND team2ID=teamID)';

这是PHP代码的其余部分,它应该在我的html页面上显示信息

 <h2>Round 1 Matchups</h2>
<table width=100%>
<tr>
    <th title="team1ID">Team</th>
    <th title="team2ID">Team</th>

</tr>

             <?php
           // Remember to replace 'username' and 'password'!
          $conn = oci_connect('xx', 'xxx', '(DESCRIPTION=(ADDRESS_LIST=
          (ADDRESS=(PROTOCOL=TCP)(Host=db2.ndsu.edu)(Port=1521)))
          (CONNECT_DATA=(SID=cs)))');


         //put your query here
        $query = 'SELECT team1ID, team2ID  FROM Matchup WHERE RoundID=1 IN 
        (SELECT teamName FROM Team WHERE team1ID=teamID AND 
         team2ID=teamID)';
        $stid = oci_parse($conn,$query);
        oci_execute($stid,OCI_DEFAULT);

        //iterate through each row
        while ($row = oci_fetch_array($stid,OCI_ASSOC)) 
        {
         echo '<tr>';
         foreach ($row as $item)
        {
          echo '<td>' . $item . '</td>';
         }
          echo '</tr>';

        echo '<br>';}
        echo '</table>';
        oci_free_statement($stid);
       oci_close($conn);
         ?>

1 个答案:

答案 0 :(得分:2)

您可以在team表格上两次加入,每个小组一次:

SELECT t1.name, t2.name
FROM   match m
JOIN   team t1 ON t1.teamid = m.team1id
JOIN   team t2 ON t2.teamid = m.team2id
WHERE  roundid = 1