我在下面有一个带有动态 where 子句的查询,但我对放置 GROUP BY 和 ORDER BY 子句的位置有疑问。我认为它根本没有被触发,因为准备语句在这些子句之前。但它并不仅仅允许我将子句行放在准备语句之上,或者它给我一个错误,在完全不同的行中说明未定义的问题。我的问题是 GROUP BY AND ORDER BY CLAUSE 应该正确放置在哪里?
代码:
$selectedstudentanswerqry = "
SELECT
sa.StudentId, StudentAlias, StudentForename, StudentSurname, q.SessionId,
...
FROM Student st
...
";
// Initially empty
$where = array('q.SessionId = ?');
$parameters = array($_POST["session"]);
$parameterTypes = 'i';
//check if POST is empty
// Check whether a specific student was selected
$p_student = empty($_POST["student"])?0:$_POST["student"]; // Now if $_POST['student'] is either 0 or empty $p_student will be 0
echo $p_student;
switch($p_student){
case 0:
//dont' add where filters
break;
default:
$where[] = 'sa.StudentId = ?';
$parameters[] .= $_POST["student"];
$parameterTypes .= 'i';
}
// If we added to $where in any of the conditionals, we need a WHERE clause in
// our query
if(!empty($where)) {
$selectedstudentanswerqry .= ' WHERE ' . implode(' AND ', $where);
global $mysqli;
$selectedstudentanswerstmt=$mysqli->prepare($selectedstudentanswerqry);
// You only need to call bind_param once
if (count($where) == 1) {
$selectedstudentanswerstmt->bind_param($parameterTypes, $parameters[0]);
}
else if (count($where) == 2) {
$selectedstudentanswerstmt->bind_param($parameterTypes, $parameters[0], $parameters[1]);
}
}
$selectedstudentanswerqry .= "
GROUP BY sa.StudentId, q.QuestionId
ORDER BY StudentAlias, q.SessionId, QuestionNo
";