我的代码下面包含一个MySQL查询:
// These gets the values entered in the drop-down lists and stores the values as
// variables.
$event = $_GET['cmbEvent'];
$yrGroup = $_GET['cmbYrGroup'];
$gender = $_GET['cmbGender'];
/* The query $eygQuery, where the 'eyg' stands for event, year group and gender,
grabs the stud_fname, stud_sname, result_studpoints, result_position, studevent_result
where the requirements of the specific stud_gender, stud_yrgroup and event_id is met */
$eygQuery = "
SELECT stud_id,
stud_fname,
stud_sname,
result_studpoints,
result_position,
studevent_result
FROM
students s
INNER JOIN
result r on
s.stud_id = r.stud_id
WHERE
stud_gender = '$gender'
AND stud_yrgroup = '$yrGroup'
AND r.event_id = '$event'
";
$result = mysqli_query($conn, $eygQuery);
由于'SELECT stud_id'(这是主键和外键)而失败。当我删除stud_id时,查询看起来像这样:
SELECT stud_fname,
stud_sname,
result_studpoints,
result_position,
studevent_result
FROM
students s
INNER JOIN
result r on
s.stud_id = r.stud_id
WHERE
stud_gender = '$gender'
AND stud_yrgroup = '$yrGroup'
AND r.event_id = '$event'
它有效,但是如何修改查询以输出stud_id呢?
提前致谢。
答案 0 :(得分:2)
stud_id
在您的查询中含糊不清。使(表示)该字段更具体:
SELECT s.stud_id,
stud_fname,
stud_sname,
result_studpoints,
result_position,
studevent_result
FROM
students s
INNER JOIN
result r on
s.stud_id = r.stud_id
WHERE
stud_gender = '$gender'
AND stud_yrgroup = '$yrGroup'
AND r.event_id = '$event'
编辑: 为了更方便的结果提取,我建议对某些选定的字段使用别名:
SELECT s.stud_id AS student_id,
....
获取数据示例(在PHP中):
...
while ($data = mysqli_fetch_assoc($result)) {
$studId = $data['student_id'];
echo $studId;
}
...
答案 1 :(得分:0)
很可能您会收到此错误,因为列名称不明确,因此您需要指定要从中获取结果的表。尝试在列名称前添加表格的简称,例如:
SELECT s.stud_id,
stud_fname,
stud_sname,
result_studpoints,
result_position,
studevent_result
FROM
students s
INNER JOIN
result r on
s.stud_id = r.stud_id
WHERE
stud_gender = '$gender'
AND stud_yrgroup = '$yrGroup'
AND r.event_id = '$event'
答案 2 :(得分:0)
stud_id
是students
和result
表中的字段集。当您要求数据库检索该数据时,他不知道要选择什么值。它足以指定从哪个表中获取该数据:
SELECT s.stud_id.
stud_fname,
stud_sname,
result_studpoints,
result_position,
ìstudevent_result
FROM
students s
INNER JOIN
result r on
s.stud_id = r.stud_id
WHERE
stud_gender = '$gender'
AND stud_yrgroup = '$yrGroup'
AND r.event_id = '$event'
答案 3 :(得分:0)
stud_id
含糊不清 - 它出现在students
和result
表格中。只需用表别名来限定它,你应该没问题:
SELECT s.stud_fname,
-- Here -^
stud_sname,
result_studpoints,
result_position,
studevent_result
FROM
students s
INNER JOIN
result r ON s.stud_id = r.stud_id
WHERE
stud_gender = '$gender'
AND stud_yrgroup = '$yrGroup'
AND r.event_id = '$event'