php - SQL在查询中添加子索引列?

标签 php mysql

我有一个大致格式如下的 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/

相关文章:

php - require 和 require-dev 有什么区别?

PHP 去除非整数并将输出重新格式化为电话号码

mysql - 在 mysql 中将日期随机更改 +- 5 天?

Mysql 查询在服务器端执行时有效,但在客户端执行时无效

c++ - QSqlDatabase断线检测

php - 使用变量定义 PHP 函数

php - 我的查询有什么问题 — mysqli_num_rows() 期望参数 1 为 mysqli_result, bool 值在

MySQL根据一行的唯一性选择DISTINCT多列?

php - PDO 从选择查询中获取一列

php - 保存到数据库的 jQuery Portlet