gpt4 book ai didi

mysql - 使用内连接SQL语句时未定义索引

转载 作者:行者123 更新时间:2023-11-29 01:35:06 25 4
gpt4 key购买 nike

您好,我正在尝试编写 SQL 语句来填充表,但我不断收到错误:

Undefined index: st.Name, and Undefined index: s.Name.

我不明白为什么会这样,因为我已经在 SQL 语句中选择了它们。我不太擅长 SQL,所以我们将不胜感激。

<?php
ini_set("display_errors", 1);
try{
$stmt = $conn->prepare(
"SELECT st.Name, s.Name
From Sports AS s INNER JOIN Choices AS c
ON s.Sport_ID = c.Sport_ID INNER JOIN Student_Choices AS sc
ON sc.T1_Choice = c.Choice_ID INNER JOIN Students AS st
ON st.Username = sc.Username
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>
<td>'.$row['st.Name'].'</td>
<td>'.$row['s.Name'].'</td>
</tr>
';
}
}
catch(PDOException $e)
{
echo "error".$e->getMessage();
}
?>

最佳答案

存在多个问题。首先,您认为您将能够使用 <table/alias-name>.<column/alias-name> 访问这些列值的假设是错误的。 。相反,只能使用列名或定义的别名来访问它们。

现在,在本例中,您有两列同名。因此,您应该为它们定义不同的别名,以避免出现歧义的行为。我已经定义了它们student_namesport_name .

定义别名后,您现在可以仅使用别名来访问这些列值。

        $stmt = $conn->prepare(
"SELECT st.Name AS student_name,
s.Name AS sport_name
From Sports AS s INNER JOIN Choices AS c
ON s.Sport_ID = c.Sport_ID INNER JOIN Student_Choices AS sc
ON sc.T1_Choice = c.Choice_ID INNER JOIN Students AS st
ON st.Username = sc.Username
");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<tr>
<td>'.$row['student_name'].'</td>
<td>'.$row['sport_name'].'</td>
</tr>
';
}

关于mysql - 使用内连接SQL语句时未定义索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53226276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com