我有一个大致格式如下的 SQL 表
+----+------------+------------+----------+------+
| id | fin_date | student_id | course_id| mark |
+----+------------+------------+----------+------+
| 1 | 2018-05-03 | 10049 | 1 | 60 |
| 2 | 2018-05-03 | 10032 | 2 | 45 |
| 3 | 2018-05-03 | 10032 | 1 | 88 |
| 4 | 2018-05-03 | 10032 | 1 | 96 |
+----+------------+------------+----------+------+
不幸的是,我刚刚被要求创建一个“student_course_id”子索引的索引,该索引表示学生在此之前已修读的类(class)数量......下面的示例
+----+------------+------------+----------+------+-------------------+
| id | fin_date | student_id | course_id| mark | student_course_id |
+----+------------+------------+----------+------+-------------------+
| 1 | 2018-05-03 | 10049 | 1 | 60 | 1 |
| 2 | 2018-05-03 | 10032 | 2 | 45 | 1 |
| 3 | 2018-05-03 | 10032 | 3 | 88 | 2 |
| 4 | 2018-05-03 | 10032 | 4 | 96 | 3 |
| 5 | 2018-05-03 | 10049 | 2 | 60 | 2 |
+----+------------+------------+----------+------+-------------------+
这样,当您在两个日期之间查找索引 id=3 时,您就可以立即知道这是该学生选修的第二门类(class)。
我真的不想在表中添加新列,有什么方法可以以类似于 COUNT(*) 的方式添加此额外列,可用于对单列中的唯一字段进行总计?
最佳答案
好吧,我想我问得有点过早了。我明白了...
SELECT *, ( select count(*) from `marks` t2
where t1.student_id = t2.student_id and t1.id >= t2.id )
as student_course_id FROM `marks` as t1
关于php - SQL在查询中添加子索引列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50165594/