两张表关联查询,学生表和学生学习记录表,学生表是学生的基本信息,学习记录主要是每天背诵的单词记录,包括单词对错的个数ifnull:如果是空则为...left join左连接,左表全部显示,右表没有匹配字段显示空left join后面一张表的查询结果,用到哪个字段查询哪个字段,没必要全部查询//班级里的学生单词背诵查询public List<RecitingStudent> findTotalStudents(int classId, Timestamp start, Timestamp end) { Session session = getSessionFactory().getCurrentSession(); String query = "SELECT s.studentId, s.name, ifnull(sum(m.correct_number),0) as correct, ifnull(sum(m.error_number),0) as error from " + "student s " + "LEFT JOIN " + "(SELECT studentId,correct_number,error_number FROM " + "reciting_notes r " + "WHERE r.uploadTime BETWEEN ? AND ?) m " + "ON " + "s.studentId = m.studentId " + "where " + "s.classId=? " + "GROUP BY s.studentId"; Query query1 = session.createSQLQuery(query).addScalar("studentId",StandardBasicTypes.INTEGER). addScalar("name",StandardBasicTypes.STRING). addScalar("correct", StandardBasicTypes.INTEGER). addScalar("error",StandardBasicTypes.INTEGER); query1.setParameter(0, start); query1.setParameter(1, end); query1.setParameter(2, classId); List list = query1.list(); List<RecitingStudent> recitingStudents = new ArrayList<>(); for(Iterator iterator = list.iterator(); iterator.hasNext();){ //每个集合元素都是一个数组,数组元素列值 Object[] objects = (Object[]) iterator.next(); RecitingStudent recitingStudent = new RecitingStudent(); recitingStudent.setStudentId((Integer) objects[0]); recitingStudent.setName((String) objects[1]); recitingStudent.setCorrect((Integer) objects[2]); recitingStudent.setError((Integer) objects[3]); recitingStudents.add(recitingStudent); } return recitingStudents; }}
hibernate关联查询纯SQL的实现(mysql)
最新推荐文章于 2021-10-25 19:11:59 发布