[英]WHERE DATE_FORMAT = DATE_FORMAT is inaccurate
我在数据库中为每个预订使用unix时间戳整数存储时间。 我遇到了一个问题,即我的查询未正确选择内容,似乎一天休息了。
例如,在我的网站上,我有一个日历表,其中显示了每月的每一天。 我使用以下代码来填充每天的产品:
$sql = "select b.*, p.name as p_name, p.color as p_color
from `bookings` as b
left join `products` as p on (p.id = b.id_product)
where date_format(from_unixtime(b.timestamp), '%M %e %Y') = date_format(from_unixtime(:timestamp), '%M %e %Y')
order by b.timestamp asc";
$stm = $this->app->db->prepare($sql);
$stm->bindParam(':timestamp', $this->timestamp);
$stm->execute();
$res = $stm->fetchAll();
现在,它显示了我日历中第25天的1月24日的预订。
问题似乎在于查询的这一部分:
where date_format(from_unixtime(b.timestamp), '%M %e %Y') = date_format(from_unixtime(:timestamp), '%M %e %Y')
例如,当$this->timestamp = '1453698000'
(第25位)和b.timestamp = '1453618800'
(第24位)时,它将在我的日历的第25位显示此记录。
我完全不知道为什么会这样。 我尝试将date_format查询更改为使用'%d-%m-%Y',尝试添加'00:00:00',尝试在PDO构造中手动设置时区,通过使用PHP date()函数回显时间戳,确保我的所有时区都正确对齐(它们是正确的)。
为什么会这样呢? 任何帮助将不胜感激。
首先,您可以运行以下命令来更彻底地调试它:
SELECT date_format(from_unixtime(1453698000), '%M %e %Y')
和
SELECT date_format(from_unixtime(1453618800), '%M %e %Y')
并查看每个结果。 这应该可以揭示问题。
我不知道您在传递unix时间戳时如何设置时区,但我认为这是不可能的。 时区用于根据通用时间戳计算本地时间和日期。
PHP认为每个时间戳都位于哪个时区并不重要,这就是为什么PHP date()函数匹配的原因。 重要的是您的MySQL引擎所在的时区,因为这是您进行转换的地方。
我会从您的应用程序中的正确日期时间(例如25:00:00)计算出确切的时间戳,并将其传递给查询。
转换本身:
where date_format(from_unixtime(b.timestamp), '%M %e %Y') = date_format(from_unixtime(:timestamp), '%M %e %Y')
使时间戳上的任何索引无效,因此可能导致性能降低。
最好这样写:
WHERE b.timestamp >= :timestamp
AND b.timestamp < :timestamp + INTERVAL 1 DAY
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.