MySQL 缓存和日期函数
我曾经在性能博客中读到,最好使用 PHP 的日期函数在 MySQL 查询中设置日期,而不是使用像 curdate() 这样的 mysql 日期函数,因为 mysql 可以缓存查询或结果或类似的东西。有人对此有任何见解吗?它有水分还是毫无根据?
示例:
$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';
对比
$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';
I once read in a performance blog that it is better to use PHP's date functions to set dates in a MySQL query instead of using mysql date functions like curdate() because mysql can then cache the query or the result or something like that. Does anyone have any insight into this? Does it hold any water or is it baseless?
example:
$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';
vs
$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
任何包含 CURDATE() 的函数都不会被缓存。 硬编码
日期仍应缓存据我所知。虽然您可能想考虑使用
prepare
功能而不是将字符串拼接到查询中(出于理智和安全考虑)。Any function containing
CURDATE()
will not be cached. SourceHardcoding the date should still be cached as far as I can tell. Though you might want to consider using the
prepare
functionality instead of splicing strings into your query (for sanity and security sake).其实很简单。 MySQL 服务器看不到您的 PHP 代码,因此它将收到以下之一:
它也不会读取您的意图。对于 MySQL,
'2010-01-18'
是一个字符串并且是确定性的:其值始终为“2010-01-18”。但是,CURDATE()
不是确定性的:它的值根据运行它的日期而变化。因此,第一个是可缓存的,而第二个则不可缓存。It's quite simple actually. The MySQL server does not see your PHP code so it'll receive one of these:
It will not read your intentions either. For MySQL,
'2010-01-18'
is a string and is deterministic: its value is always '2010-01-18'. However,CURDATE()
is not deterministic: its value varies depending on the date when you run it. Thus the first one is cacheable and the second one is not.我个人更喜欢第一种方式,因为它可以清楚地了解服务器时间(时区),我的 mysql 服务器在承诺时碰巧早了 10 小时:)
PHP 脚本中的本地时间将应用于 SQL
I personally preffer first way, because it give clear head about server time (time zone), my mysql server happend to be 10h earlier when promissed :)
localtime in your PHP script will apply in SQL