2012-11-19 108 views
0

我有一個內部聯接工作如何,當我在我的數據庫中執行一個SQL查詢。PHP陣列選擇與內部聯接

SELECT debate.date, school1.name, school2.name 
FROM debate 
INNER JOIN schools as school1 
ON debate.homeid=school1.id 
INNER JOIN schools as school2 
ON debate.awayid=school2.id 

返回

date  name  name 
19-01-2013 st Peters St Simons 

當我試着使用PHP這樣做。我使用相同的select語句,並在下面添加。

foreach ($result as $row) 
{ 
    $debates[] = array(
    'date' => $row['date'], 
    'awayschool' => $row['name'], 
    'homeschool' => $row['name'], 
); 
} 


<table> 
<tr> 
<td><?php echo $debate['date']; ?></td> 
<td><?php echo $debate['name']; ?></td> 
<td><?php echo $debate['name']; ?></td> 
</tr> 
</table> 

它返回

date  name  name 
19-01-2013 st Peters st Peters 

但是我希望它回來。

date  name  name 
19-01-2013 st Peters St Simons 

在我的陣列我嘗試了好幾種不同的東西,如與

'awayschool' => $row['school1.name'], 

更換

'awayschool' => $row['name'], 

,但我得到一個錯誤說未定義指數當我這樣做。

我在這裏做錯了什麼?

回答

2

這裏的問題是,無論school1.name和school2.name是(在php)並重命名爲$行[「名稱」],你可以使用AS將其重命名

SELECT debate.date, school1.name, school2.name AS name2 
FROM debate 
INNER JOIN schools as school1 
ON debate.homeid=school1.id 
INNER JOIN schools as school2 
ON debate.awayid=school2.id 

然後取一個改變你的foreach循環這個

foreach ($result as $row) 
{ 
    $debates[] = array(
    'date' => $row['date'], 
    'awayschool' => $row['name'], 
    'homeschool' => $row['name2'], 
); 
} 
1

修改您的查詢,像這樣

SELECT debate.date, school1.name "School1Name", school2.name "School2Name" 
FROM debate 
INNER JOIN schools as school1 
ON debate.homeid=school1.id 
INNER JOIN schools as school2 
ON debate.awayid=school2.id; 

然後:

foreach ($result as $row) 
{ 
    $debates[] = array(
    'date' => $row['date'], 
    'awayschool' => $row['School1Name'], 
    'homeschool' => $row['School2Name'], 
); 
} 
0

只需使用一個別名them.Like school1.name AS SCHLNAME1, school2.name AS SCHLNAME2 那麼這些指標會在你array.Then可用時,它會

'awayschool' => $row['SCHLNAME1'], 
'awayschool' => $row['SCHLNAME2'] 
0

嘗試改變下列

<td><?php echo $debate['date']; ?></td> 
<td><?php echo $debate['name']; ?></td> 
<td><?php echo $debate['name']; ?></td> 

到此

<td><?php echo $debate['date']; ?></td> 
<td><?php echo $debate['awayschool']; ?></td> 
<td><?php echo $debate['homeschool']; ?></td>