2013-12-12 42 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