2

如果我避免使用内置的 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',服务器端代码变得更糟:(但在 db 端我们可以使用索引

我看到使用内置函数的两个问题: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 内置的日期和时间函数,它会带来真正的利润吗?

4

2 回答 2

1

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

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

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

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

于 2013-07-01T14:37:10.617 回答
0

第二个查询在表中的每一行上运行日期函数,而第一个查询可以只使用索引来查找它需要的行。那就是最大的放缓所在。查看解释输出中的行列

于 2013-07-01T14:37:12.043 回答