Gli algoritmi delle Viste

Stai visualizzando una vecchia versione di questo article. Visualizza la versione più recente.

Spiegazione

L'istruzione CREATE VIEW accetta una clausola opzionale ALGORITHM, un'estensione SQL per le Views.

Questa può assumere tre valori: MERGE, TEMPTABLE o UNDEFINED, e influenza il modo in cui MariaDB elabora le viste.

Con MERGE, la definizione della vista e la porzione delle istruzioni che si riferiscono alla vista vengono unite. Se si usa TEMPTABLE, i risultati della vista vengono inseriti in una tabella temporanea.

MERGE di solito è più efficiente, ed è possibile aggiornare le viste solo se usano questo algoritmo. TEMPTABLE può essere utile in certe situazioni, perché i lock sulle tabelle sottostanti possono essere rilasciati prima che l'esecuzione dell'istruzione sia terminata.

Se è UNDEFINED (o la clausola ALGORITHM non è specificata), MariaDB sceglie l'algoritmo migliore. L'algoritmo può essere UNDEFINED anche se è stato specificato MERGE ma questo non può essere utilizzato.

MERGE limiti

Le viste che usano le seguenti funzionalità non possono essere di tipo ALGORITHM=MERGE:

MERGE Examples

Example 1

Here's an example of how MariaDB handles a view with a MERGE algorithm. Take a view defined as follows:

CREATE ALGORITHM = MERGE VIEW view_name (view_field1, view_field2) AS
SELECT field1, field2 FROM table_name WHERE field3 > '2013-06-01';

Now, if we run a query on this view, as follows:

SELECT * FROM view_name;

to execute the view view_name becomes the underlying table, table_name, the * becomes the fields view_field1 and view_field2, corresponding to field1 and field2 and the WHERE clause, WHERE field3 > 100 is added, so the actual query executed is:

SELECT field1, field2 FROM table_name WHERE field3 > '2013-06-01'

Example 2

Given the same view as above, if we run the query:

SELECT * FROM view_name WHERE view_field < 8000;

Here everything occurs as it does in the previous example, but view_field < 8000 takes the corresponding field name and becomes field1 < 8000, connected with AND to the field3 > '2013-06-01' part of the query.

So the resulting query is:

SELECT field1, field2 FROM table_name WHERE (field3 > '2013-06-01') AND (field1 < 8000);

When connecting with AND, parentheses are added to make sure the correct precedence is used.

Commenti

Sto caricando i commenti......
Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.