Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Toán tử số học作用于日期值在MySQL表中如何工作?

Khi áp dụng toán tử số học (+, -, *, /) trực tiếp lên cột kiểu DATE trong bảng, MySQL chuyển ngày thành số nguyên YYYYMMDD rồi thực hiện phép toán.

Ví dụ

Bảng example có cột orderdate = '2017-05-25':

mysql> SELECT * FROM example;
+------------+
| orderdate  |
+------------+
| 2017-05-25 |
+------------+

mysql> SELECT orderdate + 10 FROM example;   -- 20170525 + 10 = 20170535
+--------------+
| orderdate+10 |
+--------------+
|   20170535   |
+--------------+

mysql> SELECT orderdate * 10 FROM example;   -- 20170525 * 10 = 201705250
+--------------+
| orderdate*10 |
+--------------+
|  201705250   |
+--------------+

mysql> SELECT orderdate - 10 FROM example;   -- 20170525 - 10 = 20170515
+--------------+
| orderdate-10 |
+--------------+
|   20170515   |
+--------------+

mysql> SELECT orderdate / 10 FROM example;   -- 20170525 / 10 = 2017052.5
+--------------+
| orderdate/10 |
+--------------+
| 2017052.5    |
+--------------+

Lưu ý: Đây là hành vi ngầm (implicit conversion), không phải phép toán ngày tháng đúng đắn. Để cộng/trừ ngày đúng, hãy dùng INTERVAL (xem bài 1362).