0

当我在我的数据库中执行 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.ini 执行此操作时。我使用相同的选择语句并在下面添加。

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'],

但是当我这样做时,我得到一个错误,说未定义的索引。

我在这里做错了什么?

4

4 回答 4

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'],
  );
}
于 2012-11-19T11:16:03.733 回答
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'],
  );
}
于 2012-11-19T11:16:18.020 回答
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>
于 2012-11-19T11:19:54.940 回答
0

只需为它们使用别名。就像school1.name AS SCHLNAME1, school2.name AS SCHLNAME2 这些索引将在您的数组中可用。然后它将是

'awayschool' => $row['SCHLNAME1'],
'awayschool' => $row['SCHLNAME2']
于 2012-11-19T11:17:02.627 回答