AJAX 请求完成请求花费的时间太长

AJAX request takes too long to complete the request

我有一个 MySQL 查询,它有 17000 行。如果我使用 Putty 在 MySQL 终端中直接执行该查询,则需要 17 ~ 20 秒才能获取所有行。这可以。

但是当我尝试使用 PHP 和 AJAX 请求执行查询时,完成请求需要 50 ~ 60 秒,即使这个查询被缓存了。

我正在使用 CodeIgniter PHP 框架进行缓存及其 AJAX 请求。

我同意,与在终端中直接执行 MySQL 查询相比,HTTP 请求和 PHP 执行可能需要一些时间。

MySQL 直接查询执行:20 秒 使用 HTTP、php、Codeigniter 和 JSON 格式并缓存:60 秒。

估计时差太长了。

我正在尝试执行的模型查询:

mysql> explain SELECT col1, col2, col3, col4, IFNULL(col5,'N/A') AS 'col55', `col6`, col7, col8, col9 FROM table1 LEFT JOIN table1 ON table1.fkid_colid=`voyage id` AND table1.alias_type='voyage_display' WHERE column10='voyage';
+----+-------------+--------------+------+-------------------------------------+---------+---------+------------------------------------+-------+-------------+
| id | select_type | table        | type | possible_keys                       | key     | key_len | ref                                | rows  | Extra       |
+----+-------------+--------------+------+-------------------------------------+---------+---------+------------------------------------+-------+-------------+
|  1 | SIMPLE      | table1       | ALL  | NULL                                | NULL    | NULL    | NULL                               | 37770 | Using where |
|  1 | SIMPLE      | table1       | ref  | PRIMARY,fk_table1_colid_idx         | PRIMARY | 4       | database.table1.column ID |     1 | Using index |
+----+-------------+--------------+------+-------------------------------------+---------+---------+------------------------------------+-------+-------------+
2 rows in set (0.00 sec)

对这么长的加载时间有什么想法吗?如果您对此提出任何优化技术建议?

您的查询

SELECT 
col1, 
col2, 
col3, 
col4, 
IFNULL(col5,'N/A') AS 'col55', 
`col6`, 
col7, 
col8, 
col9 
FROM table1 
LEFT JOIN table1 ON table1.fkid_colid=`voyage id` AND table1.alias_type='voyage_display' 
WHERE column10='voyage';

从解释计划中可以很清楚地看出,where 的用法不是使用索引,而是试图扫描整个 table。

您需要添加一个索引作为

alter table table1 add index column10_idx(column10);

上面的列在where clause中使用,连接子句看起来不错,正在解析索引。

确保在应用索引之前对数据库进行备份。应用索引后检查查询速度。

是的。我刚刚通过分析控制器功能发现了问题。

根据 Codeigniter 分析结果如下,

控制器执行时间:27.7074 秒。

然后我查看了 Chrome 控制台以了解完成请求所花费的时间,由此我知道了一个问题。

Stalled : 17.32 s
DNS Lookup: 1.000 ms
Initial connection  :262.000 ms
Request/Response        TIME
Request sent    0
Waiting (TTFB)  1.03 s
Content Download    29.84 s
Total time: 48.46 s

从报告来看,最大的问题是 "Stalled" 时间。耗时 17.32 秒。这是由于我方的代理问题而发生的,这是无法避免的,也不会在我的客户方发生。所以可以忽略不计。

所以,

直接查询执行17~20秒

Ajax浏览器端请求内容下载:29~30秒

所以 3MB 内容下载的时间差是 10 秒,我的客户被接受了:)

感谢您的回复。