两张JOINS在同一张桌子上

时间:2013-06-13 16:01:54

标签: php html mysql join

我正在一个网站上显示我的数据库中有两个团队和两个分数的足球比分。

这是我的代码:

<?php 
        $result = mysql_query( "SELECT * FROM resultat 
        LEFT JOIN brukere ON resultat.dommer = brukere.id
        INNER JOIN lag ON resultat.lag1 = lag.id
            INNER JOIN lag ON resultat.lag2 = lag.id
        ORDER BY slutt DESC
        " )
        or die("SELECT Error: ".mysql_error());
        $num_rows = mysql_num_rows($result);if ($result) {while ($row = mysql_fetch_array($result)) {
        $_SESSION['id']=$row['id'];
        ?>
        <tr>
                <td><?php echo $row['klubb']; ?></td>
                <td><?php echo $row['klubb']; ?></td>
                <td><?php echo $row['stilling1'] . " - " . $row['stilling2']; ?></td>
                <td><?php echo $row['roed'] . " rødt og " . $row['gult'] . " gult"; ?></td>
                <td><?php echo $row['bane']; ?></td>
                <td><?php echo $row['navn']; ?></td>
            </tr>
        <?php
        }
        }
        ?>

我得到了:

  

SELECT错误:不唯一的表/别名:'lag'

当我尝试:

INNER JOIN lag s ON resultat.lag1 = lag.id
INNER JOIN lag c ON resultat.lag2 = lag.id

我明白了:

  

SELECT错误:'on clause'

中的未知列'lag.id'

我该怎么办?来自同一个表的两个连接

3 个答案:

答案 0 :(得分:4)

您需要使用刚刚提供给表格lag的别名。您在第一次加入时分配了s,在第二次加入了c,因此您应该使用它们

INNER JOIN lag s ON resultat.lag1 = s.id
INNER JOIN lag c ON resultat.lag2 = c.id

答案 1 :(得分:1)

你可以尝试像这样组合JOIN:

INNER JOIN lag ON resultat.lag1 = lag.id OR resultat.lag2 = lag.id

如果需要,请将OR替换为

答案 2 :(得分:0)

这是一个自我加入,你需要在你的经历中使用别名:

     INNER JOIN lag s ON resultat.lag1 = s.id
     INNER JOIN lag c ON resultat.lag2 = c.id 

一般情况下,您使用带有邻接列表的自联接并沿着维度走树:

    SELECT t1.name AS lev1, t2.name as lev2, t3.name as lev3, t4.name as lev4
    FROM category AS t1
    LEFT JOIN category AS t2 ON t2.parent = t1.category_id
    LEFT JOIN category AS t3 ON t3.parent = t2.category_id
    LEFT JOIN category AS t4 ON t4.parent = t3.category_id
    WHERE t1.parent is NULL