Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

เงื่อนไขการตรวจสอบวันครบกำหนดและวันที่ปัจจุบันใน WHERE clause ของ MySQL

ในการตรวจสอบเงื่อนไขดังกล่าว ให้ใช้ฟังก์ชัน IF() ใน MySQL

ตัวอย่าง: สร้างตาราง

mysql> create table demo89 ( duedate date ); Query OK, 0 rows affected (0.78 sec)

ตัวอย่าง: เพิ่มข้อมูลลงในตาราง

mysql> insert into demo89 values('2020-01-10'); Query OK, 1 row affected (0.55 sec)
mysql> insert into demo89 values(null); Query OK, 1 row affected (0.13 sec)
mysql> insert into demo89 values('2020-11-29'); Query OK, 1 row affected (0.15 sec)
mysql> insert into demo89 values('2019-11-29'); Query OK, 1 row affected (0.09 sec)

ตัวอย่าง: แสดงข้อมูลจากตาราง

mysql> select * from demo89;

ผลลัพธ์

+------------+
| duedate    |
+------------+
| 2020-01-10 |
| NULL       |
| 2020-11-29 |
| 2019-11-29 |
+------------+
4 rows in set (0.00 sec)

ตัวอย่าง: คิวรีตรวจสอบวันครบกำหนดและวันที่ปัจจุบัน

mysql> select if (duedate is null or duedate < curdate(),'Wrong Date',duedate) as Result from demo89;

ผลลัพธ์

+------------+
| Result     |
+------------+
| Wrong Date |
| Wrong Date |
| 2020-11-29 |
| Wrong Date |
+------------+
4 rows in set (0.00 sec)

คำอธิบาย: คิวรีนี้จะตรวจสอบว่า duedate เป็น NULL หรือ น้อยกว่าวันที่ปัจจุบัน (curdate()) ถ้าใช่จะแสดง 'Wrong Date' มิฉะนั้นจะแสดงค่า duedate เดิม