Mysql
 SQL >> Database >  >> RDS >> Mysql

È possibile l'indicizzazione tra tabelle in MySQL?

Come forse saprai, SQL Server ottiene questo risultato con le viste indicizzate. Per beneficiare di quella tecnica in SQL Server, devi interrogare la vista anziché le tabelle sottostanti, il che significa dover essere a conoscenza della vista e dei suoi indici.

MySQL non ha viste indicizzate, ma puoi simulare il comportamento con una tabella + trigger + indici. Invece di una vista, crei una tabella indicizzata più un trigger che la mantiene sincronizzata, poi interroghi quella nuova tabella invece di quelle normalizzate. Valuta però se il costo aggiuntivo in scrittura supera il miglioramento in lettura.

Modificato:

Nota che una tabella completamente nuova non è sempre necessaria. In una relazione 1:N (testa-dettaglio), ad esempio, un trigger può copiare un campo dalla tabella 'testa' in quella 'dettaglio'. Nel tuo caso:

CREATE TABLE tableOne ( id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, tableTwoId INT UNSIGNED NOT NULL, objectId INT UNSIGNED NOT NULL, desnormalized_eventTime DATETIME NOT NULL, INDEX (objectID), FOREIGN KEY (tableTwoId) REFERENCES tableTwo (id) ) ENGINE=InnoDB; CREATE TRIGGER tableOne_desnormalized_eventTime BEFORE INSERT ON tableOne for each row begin DECLARE eventTime DATETIME; SET eventTime = (select eventTime from tableOne where tableOne.id = NEW.tableTwoId); NEW.desnormalized_eventTime = eventTime; end; 

Nota che questo è un trigger BEFORE INSERT. La query diventa quindi:

select * from tableOne t1 inner join tableTwo t2 on t1.tableTwoId = t2.id where t1.objectId = '..' order by t1.desnormalized_eventTime; 

Dichiarazione di non responsabilità: non testato.