Computer >> 컴퓨터 >  >> 프로그래밍 >> MySQL

MySQL에서 현재 날짜 기준 12일 전에 결과가 발표된 학생 레코드 조회하기

현재 날짜와 학생의 성적 발표 날짜 사이의 차이를 비교하고 계산하려면 DATEDIFF() 함수를 사용하면 됩니다. 여기에 AND 연산자를 함께 활용하면 성적 점수 조건까지 추가로 필터링할 수 있습니다.

1. 테이블 생성하기

먼저 예제에 사용할 테이블을 생성합니다.

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)

2. 샘플 데이터 삽입하기

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)

3. 전체 레코드 확인하기

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)

4. 현재 날짜 확인하기

CURDATE() 함수로 오늘 날짜를 먼저 확인해 보겠습니다.

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

5. 조건에 맞는 학생 레코드 조회하기

다음은 현재 날짜 기준 12일 이전에 성적이 발표되었고, 동시에 점수가 50점을 초과하는 학생 레코드를 가져오는 쿼리입니다.

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

실행 결과는 다음과 같습니다.

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

결과 분석

Carol(78점)의 성적 발표일인 2019-10-01은 현재 날짜(2019-10-13)로부터 정확히 12일 차이가 나고, 점수도 50점을 초과하므로 두 조건을 모두 만족합니다. 반면 Chris와 Bob은 발표일 차이가 12일 미만이고, Mike는 점수가 50점 이하이기 때문에 결과에서 제외됩니다.

이처럼 DATEDIFF(날짜1, 날짜2)는 첫 번째 날짜에서 두 번째 날짜를 뺀 일 수를 반환하므로, 특정 기간이 지난 데이터를 필터링할 때 매우 유용하게 활용할 수 있습니다.