La modifica dell'ordine per direzione provoca un problema delle prestazioni
-
01-11-2019 - |
Domanda
Uso MySQL 5.6 e ho due tabelle ciascuna con righe da 16 m:
CREATE TABLE IF NOT EXISTS `newsstudios` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16855382 ;
CREATE TABLE IF NOT EXISTS `newsstudio_categories` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`newsstudio_id` int(11) NOT NULL,
`category_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `newsstudio_id` (`newsstudio_id`),
KEY `category_id` (`category_id`),
KEY `newsstudio_id_category_id` (`newsstudio_id`,`category_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=16864013 ;
Ho una domanda con l'ordine di order by newsstudios.id ASC
:
SELECT SQL_NO_CACHE id FROM `newsstudios` WHERE exists
(
select newsstudio_id from newsstudio_categories
where newsstudios.id=newsstudio_categories.newsstudio_id
and newsstudio_categories.category_id in (1303,1313,1323,1333,1343,632)
)
order by newsstudios.id limit 5;
Il risultato di questa domanda è:
+------+
| id |
+------+
| 27 |
| 47 |
| 87 |
| 110 |
| 181 |
+------+
5 rows in set (0.19 sec)
Ma quando cambio la direzione dell'ordine a DESC
Il tempo di esecuzione delle query diminuisce 100 volte:
+------+
| id |
+------+
| 98232|
| 98111|
| 95222|
| 88132|
| 78181|
+------+
5 rows in set (21 sec)
Primo: perché questo cambiamento nella direzione dell'ordine causa questa enorme differenza nelle prestazioni?
Secondo: prima di questa domanda che ho provato LEFT JOIN
e WHERE IN
query invece di WHERE EXISTS
Ma hanno un risultato duplicato che dovrei usare GROUP BY
che causa using filesort
e using temporary
che riduce molto le prestazioni. Hai qualche suggerimento per la query per avere prestazioni migliori?
Nessuna soluzione corretta
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a dba.stackexchange