Reputation: 652
I'm working on a website which shows the soccer score with two teams and two scores in my DB.
This is the code I have:
<?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
}
}
?>
And I get:
SELECT Error: Not unique table/alias: 'lag'
When I try:
INNER JOIN lag s ON resultat.lag1 = lag.id
INNER JOIN lag c ON resultat.lag2 = lag.id
I get:
SELECT Error: Unknown column 'lag.id' in 'on clause'
How do I do it? Two joins from the same table
Upvotes: 1
Views: 127
Reputation: 12592
This is a self-join and you need the alias in your expession:
INNER JOIN lag s ON resultat.lag1 = s.id
INNER JOIN lag c ON resultat.lag2 = c.id
In general you use self-joins with adjacency-list and to walk the tree down a dimension:
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
Upvotes: 0
Reputation: 845
You can try to combine JOIN like this:
INNER JOIN lag ON resultat.lag1 = lag.id OR resultat.lag2 = lag.id
Replace OR with AND if you need
Upvotes: 1
Reputation: 23510
You need to use the alias you just gave to your table lag
. You assigned s
at first join and c
at second so you should use them
INNER JOIN lag s ON resultat.lag1 = s.id
INNER JOIN lag c ON resultat.lag2 = c.id
Upvotes: 4