gpt4 book ai didi

php - 绑定(bind)参数的 MySQL 性能问题

转载 作者:行者123 更新时间:2023-11-30 22:03:55 25 4
gpt4 key购买 nike

仅当我绑定(bind)参数时,我才遇到特定查询的奇怪性能问题。

这是我的代码:

$statement = $connection->prepare('SELECT count(item_id) AS count FROM MyView WHERE active = 1 AND context_id = 5 AND snapshot_id = 24');
$time_start = microtime_float();
$statement->execute();
$time_end = microtime_float();
$time1 = round($time_end - $time_start, 4);
$result = $statement->fetch()['count'];

$statement = $connection->prepare('SELECT count(item_id) AS count FROM MyView WHERE active = :filter_active AND context_id = :filter_context_id AND snapshot_id = :filter_snapshot_id');
$statement->bindValue('filter_active', 1, 2);
$statement->bindValue('filter_context_id', 5, 2);
$statement->bindValue('filter_snapshot_id', 24, 2);
$time_start = microtime_float();
$statement->execute();
$time_end = microtime_float();
$time2 = round($time_end - $time_start, 4);
$result = $statement->fetch()['count'];
enter code here

时间结果:

time1 = 0.79 sec
time2 = 31.50 sec

有人能解释一下为什么我们会出现如此巨大的性能差异吗?

谢谢

编辑和解决方案:参数类型错误。我应该改用 PDO::PARAM_INT。请注意,如果我不指定参数类型,则性能会很差。

最佳答案

哦,这个问题评论有多少问题!

  • 请提供SHOW CREATE TABLE——我们需要查看数据类型、索引和引擎(至少)。
  • 为了更快地运行,以任意顺序在 (active, context_id, snapshot_id) 上建立索引。
  • count(*)代替count(item_id)。前者是当您需要测试 item_id 是否为 NULL 时。
  • WHERE int_col = 123WHERE int_col = "123" 在性能和效果上几乎完全相同。一个不好的组合是 WHERE char_col = 123 —— 在这种情况下,它在比较之前将每个 char_col 转换为一个数字;这使得索引毫无用处。
  • 0.0005 sec 很可能是伪造的。您可能打开了查询缓存——最近运行查询时会发生这种情况,缓存在 QC 中,然后再次运行。它不会重新执行查询,而只是从 QC 中提取结果集。
  • 对于“诚实”的计时,使用 SELECT SQL_NO_CACHE ... 来避免 QC。然后运行它两次(并采取第二次计时)以避免 I/O 缓存。

关于php - 绑定(bind)参数的 MySQL 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42389090/

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