如何将日期和时间字段转换为正确的日期时间格式以在 MySQL 中进行 NOW() 比较?
How to convert date and time fields to right datetime format for NOW() comparsion in MySQL?
我使用 MySQL 5.7,我有这个查询:
SELECT
publish_date,
publish_time,
CONCAT(publish_date, ' ', publish_time) <= NOW() AS is_visible
FROM posts
ORDER BY
publish_date DESC,
publish_time DESC
LIMIT 3;
当前时间戳为:2021-08-06 15:17:00
我得到这个结果:
| publish_date | publish_time | is_visible |
+--------------+--------------+------------+
| 2021-08-06 | 17:00:00 | 0 |
| 2021-08-06 | 14:00:00 | 0 |
| 2021-07-31 | 08:00:00 | 1 |
但我等待这个结果,因为 14:00:00 时间已经过去:
| publish_date | publish_time | is_visible |
+--------------+--------------+------------+
| 2021-08-06 | 17:00:00 | 0 |
| 2021-08-06 | 14:00:00 | 1 |
| 2021-07-31 | 08:00:00 | 1 |
我尝试将日期和时间字段转换为真实的日期时间或时间戳对象,但没有帮助。
如何在 MySQL 5.7 中得到这个结果?
您可以使用内置的 TIMESTAMP(date,time)
SELECT
publish_date,
publish_time,
TIMESTAMP(publish_date,publish_time) <= NOW() AS is_visible
FROM posts
ORDER BY
publish_date DESC,
publish_time DESC
LIMIT 3;
我使用 MySQL 5.7,我有这个查询:
SELECT
publish_date,
publish_time,
CONCAT(publish_date, ' ', publish_time) <= NOW() AS is_visible
FROM posts
ORDER BY
publish_date DESC,
publish_time DESC
LIMIT 3;
当前时间戳为:2021-08-06 15:17:00
我得到这个结果:
| publish_date | publish_time | is_visible |
+--------------+--------------+------------+
| 2021-08-06 | 17:00:00 | 0 |
| 2021-08-06 | 14:00:00 | 0 |
| 2021-07-31 | 08:00:00 | 1 |
但我等待这个结果,因为 14:00:00 时间已经过去:
| publish_date | publish_time | is_visible |
+--------------+--------------+------------+
| 2021-08-06 | 17:00:00 | 0 |
| 2021-08-06 | 14:00:00 | 1 |
| 2021-07-31 | 08:00:00 | 1 |
我尝试将日期和时间字段转换为真实的日期时间或时间戳对象,但没有帮助。
如何在 MySQL 5.7 中得到这个结果?
您可以使用内置的 TIMESTAMP(date,time)
SELECT
publish_date,
publish_time,
TIMESTAMP(publish_date,publish_time) <= NOW() AS is_visible
FROM posts
ORDER BY
publish_date DESC,
publish_time DESC
LIMIT 3;