วิธีค้นหาข้อมูลโดยวันที่ในคอลัมน์ TIMESTAMP ของ MySQL
ใช้ฟังก์ชัน DATE() แยกส่วนวันที่ออกจาก TIMESTAMP ก่อนเปรียบเทียบ หรือใช้ช่วงเวลา (Range Query) เพื่อประสิทธิภาพดัชนี
ตัวอย่างการใช้งาน
สร้างตารางมีคอลัมน์ TIMESTAMP:
mysql> create table DemoTable (
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentAdmissionDate timestamp
);
เพิ่มข้อมูล:
mysql> insert into DemoTable(StudentAdmissionDate) values('2011-01-12 12:34:43');
mysql> insert into DemoTable(StudentAdmissionDate) values('2012-10-23 11:32:21');
mysql> insert into DemoTable(StudentAdmissionDate) values('2001-02-14 05:12:01');
mysql> insert into DemoTable(StudentAdmissionDate) values('2018-12-31 15:10:04');
mysql> insert into DemoTable(StudentAdmissionDate) values('2019-04-16 11:04:10');
ข้อมูลทั้งหมด:
+-----------+----------------------+ | StudentId | StudentAdmissionDate | +-----------+----------------------+ | 1 | 2011-01-12 12:34:43 | | 2 | 2012-10-23 11:32:21 | | 3 | 2001-02-14 05:12:01 | | 4 | 2018-12-31 15:10:04 | | 5 | 2019-04-16 11:04:10 | +-----------+----------------------+
วิธีที่ 1: ใช้ DATE() (เข้าใจง่าย แต่อาจไม่ใช้ Index)
mysql> select * from DemoTable where date(StudentAdmissionDate) = '2001-02-14';
+-----------+----------------------+ | StudentId | StudentAdmissionDate | +-----------+----------------------+ | 3 | 2001-02-14 05:12:01 | +-----------+----------------------+
วิธีที่ 2: ใช้ Range Query (แนะนำ - ใช้ Index ได้)
mysql> select * from DemoTable
where StudentAdmissionDate >= '2012-01-01'
and StudentAdmissionDate < '2019-12-01';
+-----------+----------------------+ | StudentId | StudentAdmissionDate | +-----------+----------------------+ | 2 | 2012-10-23 11:32:21 | | 4 | 2018-12-31 15:10:04 | | 5 | 2019-04-16 11:04:10 | +-----------+----------------------+
เหตุผลที่ Range Query ดีกว่า: MySQL สามารถใช้ Index บน StudentAdmissionDate ได้โดยตรง | วิธี DATE(column) ต้องคำนวณฟังก์ชันทุกแถว (Full Table Scan) เว้นแต่จะมี Functional Index (MySQL 8.0+)