I've been debugging this for hours and would greatly appreciate any help to see if I'm missing something very obvious. I have a MySQL table with 30k rows. The schema is as follows:
CREATE TABLE `log` (
`ip` varchar(15) COLLATE utf8mb4_unicode_520_ci NOT NULL,
`date` int(11) NOT NULL,
`requested` mediumtext COLLATE utf8mb4_unicode_520_ci NOT NULL,
`response` mediumtext COLLATE utf8mb4_unicode_520_ci NOT NULL,
`id` bigint(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;
Indexes are:
ALTER TABLE `logs`
ADD PRIMARY KEY (`id`) USING BTREE,
ADD KEY `date` (`date`);
In phpmyadmin, when I query for SELECT ip, date, requested FROM log ORDER BY date DESC LIMIT 0, 1000
, the query takes a few ms. However, in my PHP code, when I do the same query:
$mysqli = new mysqli(...);
$s = microtime(true);
$mysqli->set_charset('utf8mb4');
$query = $mysqli->prepare('SELECT ip, date, requested FROM log ORDER BY date DESC LIMIT 0, 1000');
$query->execute();
$query->bind_result($ip, $date, $requested);
while($query->fetch()) {
// ... just echoing the results
}
$e = microtime(true);
echo $e - $s;
It takes 6-7 seconds. The column id
is the primary key, and indexes are set to PRIMARY
and date
.
Some observations and debugging steps:
If I remove the
set_charset
, it takes 1.5 seconds.If I keep the
utf8mb4
charset but only selectip
anddate
, the query finishes in ~0.002 seconds.I searched online for solutions, and e.g. this solution did not make any difference.
EXPLAIN
indicates thatpossible_keys
isnull
, which is odd because it seems likedate
should be used as the index. EvenFORCE INDEX
does not make it use the index.This was working fine before I changed the collation to
utf8mb4_unicode_520_ci
-- it was utf8_unicode before.
What am I missing? How can I speed up this query to something reasonable? Thank you so much in advance!! :)