在 MYSQL 中获取在当前日期前 12 天公布结果的学籍记录


为此,你需要比较并找出当前日期和学生成绩日期之间的差异。这可以使用 AND 运算符以及 DATEDIFF() 函数来完成。

让我们首先创建一个表 −

mysql> create table DemoTable1547
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20),
   -> StudentMarks int,
   -> StudentResultDeclareDate datetime
   -> );
Query OK, 0 rows affected (0.55 sec)

使用 insert 命令插入一些记录到表中 −

mysql> insert into DemoTable1547(StudentName,StudentMarks,StudentResultDeclareDate) values('Chris',56,'2019-10-13 13:00:00')
   -> ;
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1547(StudentName,StudentMarks,StudentResultDeclareDate) values('Bob',60,'2019-10-13 12:00:00');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1547(StudentName,StudentMarks,StudentResultDeclareDate) values('Mike',45,'2019-10-13 14:00:00');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1547(StudentName,StudentMarks,StudentResultDeclareDate) values('Carol',78,'2019-10-01 14:00:00');
Query OK, 1 row affected (0.11 sec)

使用 select 语句从表中显示所有记录 −

mysql> select * from DemoTable1547;

这将生成以下输出 −

+-----------+-------------+--------------+--------------------------+
| StudentId | StudentName | StudentMarks | StudentResultDeclareDate |
+-----------+-------------+--------------+--------------------------+
|         1 | Chris       |           56 | 2019-10-13 13:00:00      |
|         2 | Bob         |           60 | 2019-10-13 12:00:00      |
|         3 | Mike        |           45 | 2019-10-13 14:00:00      |
|         4 | Carol       |           78 | 2019-10-01 14:00:00      |
+-----------+-------------+--------------+--------------------------+
4 rows in set (0.00 sec)

当前日期如下 −

mysql> select curdate();
+------------+
| curdate()  |
+------------+
| 2019-10-13 |
+------------+
1 row in set (0.00 sec)

以下查询用来获取在当前日期前 12 天公布结果的学生记录 −

mysql> select * from DemoTable1547 where datediff(curdate(),StudentResultDeclareDate) >=12 and StudentMarks > 50;

这将生成以下输出 −

+-----------+-------------+--------------+--------------------------+
| StudentId | StudentName | StudentMarks | StudentResultDeclareDate |
+-----------+-------------+--------------+--------------------------+
|         4 | Carol       | 7          8 | 2019-10-01 14:00:00      |
+-----------+-------------+--------------+--------------------------+
1 row in set (0.00 sec)

更新于: 12-Dec-2019

159 次浏览

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告