gpt4 book ai didi

php - MySQL DATETIME 函数美与性能(速度)

转载 作者:行者123 更新时间:2023-11-29 03:04:49 25 4
gpt4 key购买 nike

如果我避免使用内置的 mysql 日期和时间函数,sql 会快多少(以 % 表示)?

我是什么意思?例如:SELECT id FROM table WHERE WEEKOFYEAR(inserted)=WEEKOFYEAR(CURDATE())

MySQL 有很多内置函数来处理日期和时间,它们也适用。但是性能呢?

上面的sql不用内置函数也可以重写,比如:SELECT id FROM table WHERE inserted BETWEEN 'date for 1 day of particular week 00:00:00' AND 'last day of particular week 23:59:59' ,服务器端代码变得更糟 :( 但在数据库端我们可以使用索引

我发现使用内置函数有两个问题:1.指标

我做了小测试

mysql> explain extended select id from table where inserted between '2013-07-01 00:00:00' and '2013-07-01 23:59:59';
+----+-------------+-------+-------+---------------+------+---------+------+------+----------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+-------+---------------+------+---------+------+------+----------+--------------------------+
| 1 | SIMPLE | table | range | ins | ins | 4 | NULL | 7 | 100.00 | Using where; Using index |
+----+-------------+-------+-------+---------------+------+---------+------+------+----------+--------------------------+

mysql> explain extended select id from table where date(inserted)=curdate();
+----+-------------+-------+-------+---------------+------+---------+------+--------+----------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------+-------+---------------+------+---------+------+--------+----------+--------------------------+
| 1 | SIMPLE | table | index | NULL | ins | 4 | NULL | 284108 | 100.00 | Using where; Using index |
+----+-------------+-------+-------+---------------+------+---------+------+--------+----------+--------------------------+

第一个用了 0.00 秒,第二个在第一个之后运行并用了 0.15。一切都是用少量数据制作的。

第二个问题是

  1. 调用该函数的时间

如果在 table我有 10 亿条记录,这意味着 WEEKOFYEAR、DATE 等等……会被调用很多次,我们有那么多记录,对吗?

那么问题是,如果我停止使用 mysql 内置的日期和时间函数,它会带来真正的利润吗?

最佳答案

WHERE 子句或 JOIN 条件中使用列的函数将阻止在列上使用索引(如果存在此类索引)。这是因为对列的原始值进行了索引,而不是计算值。

请注意,上面的内容不适用于这样的查询:

SELECT id FROM atable WHERE inserted = CURDATE(); -- the raw value of "inserted" is used in the comparison

是的,最重要的是,该函数将针对扫描的每一行执行。

关于php - MySQL DATETIME 函数美与性能(速度),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17407004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com