2013-12-12 75 views
0

我有兩個表(匹配,團隊)。在比賽表中,我有id,team1,team2(其中team1和team2是球隊的ID)。在team表中我有id和name ..我如何在php中打印比賽結果,但是顯示球隊名稱而不是他們的ID?內部加入PHP

我的代碼(印刷只teamid VS teamid):

<?php 
    require_once 'conf/conf.php'; 
    require_once 'functions.php'; 
    $query = mysql_query("SELECT time1 as t1id, time2 as t2id 
         FROM matches 
         INNER JOIN teams 
         ON 
         teams.id = matches.time1 
         "); 
    //echo mysql_num_rows($query); 
    while ($row = mysql_fetch_assoc($query)) 
    { 
     $t1 = $row["t1id"]; 
     $t2 = $row["t2id"];  
     echo ($t1 . " vs. " . $t2 . "<br>"); 
    } 
?> 
+1

'var_dump($ row)'應該回答你的問題。 –

+0

使用索引和別名連接表兩次。 – rishta

回答

4

你可以做這樣的事情(假設teams表有一個name列):

<?php 
    require_once 'conf/conf.php'; 
    require_once 'functions.php'; 
    $query = mysql_query("SELECT time1 as t1id, 
           time2 as t2id, 
           t1.name AS t1name, 
           t2.name AS t2name 
         FROM matches 
         INNER JOIN teams AS t1 
         ON t1.id = matches.time1 
         INNER JOIN teams AS t2 
         ON t2.id = matches.time2"); 
    //echo mysql_num_rows($query); 
    while ($row = mysql_fetch_assoc($query)) 
    { 
     $t1 = $row["t1name"]; 
     $t2 = $row["t2name"];  
     echo ($t1 . " vs. " . $t2 . "<br>"); 
    } 
?> 
+0

作品像魅力,謝謝! –

+0

@Raphael沒問題! – Leng

2

試試這個

require_once 'conf/conf.php'; 
require_once 'functions.php'; 
$query = mysql_query("SELECT teams1.id as t1id,teams1.name as name1, teams2.id as t2id, teams2.name as name2 
        FROM matches 
        INNER JOIN teams as teams1 ON teams1.id = matches.time1 
        INNER JOIN teams as teams2 ON teams2.id = matches.time2 
        "); 
//echo mysql_num_rows($query); 
while ($row = mysql_fetch_assoc($query)) 
{ 
    $t1 = $row["name1"]; 
    $t2 = $row["name2"];  
    echo ($t1 . " vs. " . $t2 . "<br>"); 
} 
0

正如我在對您的問題的評論中所說的,請兩次加入表格:

SELECT t1.name, t2.name 
FROM matches.m 
INNER JOIN teams AS t1 ON (t1.id = m.team1) 
INNER JOIN teams AS t2 ON (t2.id = m.team2) 
+0

請給答案添加一些解釋。 – tcooc