如何在sql中划分学生

时间:2016-12-26 14:40:21

标签: php mysql sql loops mysqli

我想分组学生并将其存储在数据库中

students 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15.....20

示例: Total no.of students 20

每组4名学生(1,2,3,4组1和5,6,7,8组2等)

然后应该创建5个组

我尝试了这样的错误,我正在做的循环。

$studentQuery = $conn->query("
select s.student_pid,i.email,s.student_email,s.student_fname,
s.student_lname,s.profile_pic from r_job_invitations i 
LEFT JOIN 
tbl_students s 
ON 
i.email = s.student_email 
where i.id_job = ".$jobID." and inv_res = 1");

$totalIndividuals    = mysqli_num_rows($studentQuery);
$groups = round($totalIndividuals/5,0,PHP_ROUND_HALF_DOWN);
   for ($j = 1; $j <= $groups; $j++) {
        for ($i = 0; $i <= $totalIndividuals; $i++) {
            $GroupsQuery = $conn->query("INSERT INTO 
                r_test_group (student_id,job_id,group_name) 
                values ('".$studentResults['student_pid']."',
                           '".$jobID."','Group'".$j." )");
        }
    }

4 个答案:

答案 0 :(得分:1)

考虑到记录之间没有差距

select Concat('group',(your_col - 1 ) / 4 +  1 )
From yourtable

注意:当存在空白时,这将。如果您有间隙,那么您需要为每行生成行号,然后在我的查询中用行号替换student_id

答案 1 :(得分:1)

您可以使用地板将学生ID转换为组ID:

INSERT INTO r_test_group 
(student_id,job_id,group_name) 
SELECT student_pid, id_job, CONCAT('group', FLOOR((student_id - 1) / 4) + 1))
FROM   tbl_students s 
JOIN   r_job_invitations j ON j.email = s.student_email

答案 2 :(得分:1)

我认为您的代码会为您提供更多的学生,然后您正在寻找。在你的代码中,在第一个循环中,它运行多个组的时间,然后为下一个for循环中的每个组运行,为每个组中的所有学生运行。

 $limit = (int)($totalIndividuals/$groups);
  for($j =0; $j<$groups;)
  {
    for($i =0; $i<$totalIndividuals; $i++)
    {

     if($i % $limit == 0)
              $j++;
      $GroupsQuery = $conn->query("INSERT INTO r_test_group (student_id,job_id,group_name) values ('".$studentResults['student_pid']."', '".$jobID."','Group'".$j." )");
  }
}

答案 3 :(得分:1)

$stuData = array();
while($studentResults = $studentQuery->fetch_array())   {
    $stuData[] = $studentResults;
}
$totalIndividuals    = mysqli_num_rows($studentQuery);
$groups = round($totalIndividuals/$gd_individuals,0,PHP_ROUND_HALF_DOWN);
$count=0;
for($j = 0; $j<$groups; $j++)   {
    for($i =0; $i< $gd_individuals; $i++)   {
        if($stuData[$count]['student_pid']) {
            echo "INSERT INTO r_test_group (student_id,job_id,group_name) values (".$stuData[$count]['student_pid'].", ".$jobID.",Group".$j." )";
            $count++;
        }
    }
}
exit;

第一个forloop是分组。 第二个forloop是为学生划分。