这是我的疑问:
$subquery = "(SELECT `id`, `mark`, `date`, `session` FROM `student_marks` WHERE `student_id` = '" . $studentId . "')";
$q = $this->select()
->distinct()
->setIntegrityCheck(false)
->from($this->_name, array('name AS subjectName', 'student_marks' => new Zend_Db_Expr($subquery)))
->joinLeft('class_teachers', 'class_teachers.subject_id = subjects.id', '')
->joinLeft('teachers', 'teachers.id = class_teachers.teacher_id', array('teachers.name AS teacherName', 'teachers.family AS teacherFamily'))
->joinLeft('student_session_marks', 'student_session_marks.subject_id = subjects.id', array('student_session_marks.id AS sessionMarkId', 'student_session_marks.mark AS sessionMarkName', 'student_session_marks.session AS sessionMarkSession'))
->where('student_session_marks.student_id = ?', $studentId);
打印查询:
SELECT DISTINCT `subjects`.`name` AS `subjectName`,
(SELECT `id`, `mark`, `date`, `session` FROM `student_marks` WHERE `student_id` = '6') AS `student_marks`,
`teachers`.`name` AS `teacherName`, `teachers`.`family` AS `teacherFamily`, `student_session_marks`.`id` AS `sessionMarkId`,
`student_session_marks`.`mark` AS `sessionMarkName`, `student_session_marks`.`session` AS `sessionMarkSession`
FROM `subjects`
LEFT JOIN `class_teachers` ON class_teachers.subject_id = subjects.id
LEFT JOIN `teachers` ON teachers.id = class_teachers.teacher_id
LEFT JOIN `student_session_marks` ON student_session_marks.subject_id = subjects.id
WHERE (student_session_marks.student_id = '6')
当我删除子查询时,我的查询工作成功,否则会出现此错误:
SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 1 column(s).
答案 0 :(得分:0)
这是操作符错误...当您对select进行内部查询时,它必须只返回1列1个记录,而不是多行/多列数据集。
与任何任务一样,解决任务的方法很少,并且要获得最佳解决方案,需要清楚地了解您要做的事情......
根据您的代码,我认为以下是您正在寻找的内容:
public function getStudentSubjectMarks($studentId)
{
// cast your input (assume it's numeric...
$studentId = (int) $studentId;
//
$db = $this->getAdapter();
$q = $db->select()
->distinct()
->from($this->_name, array('name AS subjectName'))
->joinLeft('class_teachers', 'class_teachers.subject_id = subjects.id')
->joinLeft('teachers', 'teachers.id = class_teachers.teacher_id', array(
'teachers.name AS teacherName',
'teachers.family AS teacherFamily',
))
->joinLeft('student_session_marks', 'student_session_marks.subject_id = subjects.id', array(
'student_session_marks.id AS sessionMarkId',
'student_session_marks.mark AS sessionMarkName',
'student_session_marks.session AS sessionMarkSession'
))
->where('student_session_marks.student_id = ?', $studentId);
$data = array();
foreach ($db->fetchAll($q) as $record) {
$queryMarks = $db->select()
->from('student_marks', array('id', 'mark', 'date', 'session'))
->where('student_id = ?', $studentId);
// add marks to the student record
$record['student_marks'] = $db->fetchAll($queryMarks);
// add to main return array
$data[] = $record;
}
// more logic...
return $data;
}