计算并显示每个记录号

时间:2019-04-18 17:11:03

标签: mysql

假设我在下面有两个表格示例

第一个表

CREATE TABLE `student` (
  `student_id` int(11) NOT NULL,
  `student_name` varchar(255) NOT NULL,
  `class_id` int(11) NOT NULL,
);

示例数据

1,James,1
2,Dorris,1
3,Maximus,2
4,Paul,1 

第二张桌子

CREATE TABLE `class` (
  `class_id` int(11) NOT NULL,
  `class_name` varchar(255) NOT NULL,
);

示例数据

1, Red 
2, Blue 

对于每条学生记录,我想给出一些序列号,例如

班级名称/班级总数/记录编号

詹姆斯的例子-红色/ 3/1多丽丝-红色/ 3/2 保罗-红色/ 3/3

最大值-蓝色/ 1/1

到目前为止我做了什么

$result="SELECT * FROM class where class_id='1' ";
     $result=mysqli_query($connection,$result);
      $row=mysqli_fetch_array($result);
  $class_name=$row['class_name'];


$getstudent="SELECT * FROM student where class_id='1' and student_id='1'";
     $result=mysqli_query($connection,$getstudent);
      $totalstudent=mysqli_num_rows($getstudent);

      echo "$class_name/$totalstudent/";

我如何获取记录号,我认为在查询中使用计数。.我需要帮助

3 个答案:

答案 0 :(得分:0)

尝试此解决方案:)

 $sql = "SELECT T0.student_id as studentId,  T0.student_name as studentName, 
 T0.class_id as classId, T1.class_name as className, (SELECT COUNT(*) FROM 
 student WHERE class_id = T1.class_id) as totalStudents FROM student T0 
 INNER JOIN class T1 ON T0.class_id = T1.class_id";

 $result = mysqli_query($conn,$sql);
 while($row = mysqli_fetch_array($result)){
     $studentName = $row["studentName"];
     $classId = $row["classId"];
     $className = $row["className"];
     $totalStudents = $row["totalStudents"];
     if(!isset($record[$classId])){
        $record[$classId] = 0;
     }
     $record[$classId] = $record[$classId] + 1;

     // Print results
     printf("<b>".$studentName."</b></br> Class name: ".$className." 
     </br> 
     Total students: ".$totalStudents."</br> Record number: 
     ".$record[$classId]."</br></br><hr></br> ");
 }

答案 1 :(得分:0)

尝试此SELECT,然后查看结果 您可以根据需要在PHP脚本中合并列 我不测试它,如果您在行转换程序方面也遇到问题,也可以在脚本中进行设置,或者查看此帖子generate an integer sequence in MySQL

 <select id="choices1" class="form-control" name="choices-multiple-remove-button" placeholder="Compétences" multiple>

答案 2 :(得分:0)

加入2个表并创建新列,如下所示:

SELECT 
  s.*,
  concat(
    c.class_name, '/',
    (SELECT count(*) FROM student WHERE class_id = s.class_id), '/',
    (SELECT count(*) FROM student WHERE class_id = s.class_id AND student_id < s.student_id) + 1
  ) serial 
FROM student s INNER JOIN class c
ON c.class_id = s.class_id

请参见demo
结果:

| student_id | student_name | class_id | serial   |
| ---------- | ------------ | -------- | -------- |
| 1          | James        | 1        | Red/3/1  |
| 2          | Dorris       | 1        | Red/3/2  |
| 3          | Maximus      | 2        | Blue/1/1 |
| 4          | Paul         | 1        | Red/3/3  |