Mysql服务器设置为缓存:
query_cache_size = 1G
query_cache_type = 1
当我第一次从 phpmyadmin 执行查询时,查询耗时 2 秒,第二次耗时 0.0001 秒。
所以缓存确实有效。但是在 php 脚本中,查询每次都需要 2 秒。
php version 5.4.14
mysql 5.5.30
脚本:
<?php
$db = new mysqli("localhost", "user", "pass", "search");
$t = microtime(true);
$res = $db-> query("SELECT
i.page_id,
SUM(i.weight) as w
FROM
search.search_index i
INNER JOIN
search.word_full w1
ON w1.word=i.word
INNER JOIN
search.word_full w2
ON w1.word_base=w2.word_base
WHERE
w2.word = 'api'
GROUP BY
i.page_id
ORDER BY NULL");
print($res->num_rows."\n");
print(microtime(true) - $t);
?>
<?php
$link = mysql_connect("localhost", "root", "pass");
mysql_select_db("search");
$t = microtime(true);
$res = $db-> query("SELECT
i.page_id,
SUM(i.weight) as w
FROM
search.search_index i
INNER JOIN
search.word_full w1
ON w1.word=i.word
INNER JOIN
search.word_full w2
ON w1.word_base=w2.word_base
WHERE
w2.word = 'api'
GROUP BY
i.page_id
ORDER BY NULL");
print(mysql_num_rows($res)."\n");
print(microtime(true) - $t);
?>
如果我试试这个:
$t = microtime(true);
$res = $db-> query("SELECT
i.page_id,
SUM(i.weight) as w
FROM
search.search_index i
INNER JOIN
search.word_full w1
ON w1.word=i.word
INNER JOIN
search.word_full w2
ON w1.word_base=w2.word_base
WHERE
w2.word = 'api'
GROUP BY
i.page_id
ORDER BY NULL");
print(mysql_num_rows($res)."\n");
print(microtime(true) - $t."\n");
$t = microtime(true);
$res = $db-> query("SELECT
i.page_id,
SUM(i.weight) as w
FROM
search.search_index i
INNER JOIN
search.word_full w1
ON w1.word=i.word
INNER JOIN
search.word_full w2
ON w1.word_base=w2.word_base
WHERE
w2.word = 'api'
GROUP BY
i.page_id
ORDER BY NULL");
print(mysql_num_rows($res)."\n");
print(microtime(true) - $t."\n");
?>
脚本返回
235899
1.8554458618164
235899
1.8542320728302
Mysql缓存也不起作用。
表结构:
CREATE TABLE IF NOT EXISTS `search_index` (
`page_id` varchar(32) NOT NULL,
`word` varchar(32) NOT NULL,
`weight` int(11) NOT NULL,
PRIMARY KEY (`word`,`page_id`),
KEY `page_id` (`page_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `word_full` (
`word` varchar(32) NOT NULL,
`word_base` varchar(32) NOT NULL,
PRIMARY KEY (`word`,`word_base`),
UNIQUE KEY `word_base` (`word_base`,`word`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;