php - SQL add sub-index column on query?
问题描述
I have an SQL table in the following approximate format
+----+------------+------------+----------+------+
| 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 |
+----+------------+------------+----------+------+
Unfortunately, I have just been asked to then have an index for a "student_course_id" sub-index that represents the number of courses that student had taken up until that time... Example below
+----+------------+------------+----------+------+-------------------+
| 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 |
+----+------------+------------+----------+------+-------------------+
This way when you lookup index id=3 between two dates, you then can immediately tell that its the 2nd course that student has taken.
I don't really want to add a new column to my table, is there any way to add this extra column in a similar way to COUNT(*) can be used to total unique fields in a single column?
解决方案
好吧,我想我问得有点过早了。我想到了...
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
推荐阅读
- c - 如何在使用 C 的 Linux 线程中修复“从套接字读取错误 - 文件描述符错误”?
- solr - 如何在 solr 上查看文本日志文件?
- angular - 在 Angular 2 向导中更改按钮的标签
- javascript - 如何在地图(html)坐标上设置图像或颜色?
- python - 如何使用 re.sub 将捕获组的内容替换为字符串?
- php - 乘法并输出和mysql php
- java - 如果字符串包含 Hamcrest containsInAnyOrder 匹配
- jquery - jQuery 与内联 CSS 冲突
- azure-logic-apps - 从 Azure 访问 On-Prem SQL Server,而无需在两者之间使用 On-Prem 数据网关
- windows - 我的 Docker 应用程序映像的文件大小会大于基本映像吗?