mysql - 统计并显示每条记录数

标签 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 

对于每个学生记录,我想提供一些序列号,例如

类(class)名称/类(class)学生总数/记录编号

詹姆斯的示例 - 红色/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/";

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

最佳答案

连接两个表并创建新列,如下所示:

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  |

关于mysql - 统计并显示每条记录数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55750833/

相关文章:

php - 无法从 MySQL 获取数据

mysql - 优化 SQL 以获取行数

python - Flask-SQLAlchemy with_for_update() 返回旧数据

mysql - 从 native 查询中的 sails 的 MySql 数据库中选择

mysql - 查找两个纬度/经度点之间距离的最快方法

mysql - 如果条件为 true 则运行 MySQL 查询,否则运行另一个查询

mysql - 使用 SequelPro 将表格导出到 csv 文件

mysql - 通过传递数组从数据库中检索记录

mysql - 如果行存在,如何更新非唯一列否则更新 [MySQL] 中的不同行?

php - MySQL:如何做日报?