当我在数据库中执行sql查询时,我有一个内部联接工作我想要它。
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['name'],
与
'awayschool' => $row['school1.name'],
但是当我这样做时,我收到一个错误,指出未定义的索引。
我在这里做错了什么?
答案 0 :(得分:2)
这里的问题是school1.name和school2.name都是(在php中)都命名为$ row ['name'],你可以使用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 :(得分: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'],
);
}
答案 2 :(得分:0)
只需为他们使用别名。就像school1.name AS SCHLNAME1, school2.name AS SCHLNAME2
那么这些索引将在你的数组中可用。然后它将是
'awayschool' => $row['SCHLNAME1'],
'awayschool' => $row['SCHLNAME2']
答案 3 :(得分: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>