Domanda

Ho una tabella per un progetto statistico.

La struttura è così:

CREATE TABLE NewStatHistory (
    StatHistoryID uniqueidentifier PRIMARY KEY NOT NULL,
    DateEntered dateTime NOT NULL,
    DateApplies dateTime NOT NULL,
    WhoEnteredID uniqueIdentifier NOT NULL,
    PostingID uniqueIdentifier NULL,
    EnteredValue decimal(19,5) NOT NULL,
    StatID uniqueIdentifier NOT NULL,
    StatStatus int NOT NULL,
    Notes varchar(500) NULL,
    CampusID uniqueidentifier NOT NULL,
    IsTarget bit NOT NULL DEFAULT 0
)

Devo estrarre l'ultimo valore inserito per ogni " DateApplies " ;.

Questa query viene eseguita quasi istantaneamente in SqlServer ma in SQLite scade appena e non riesco a capire come ottimizzare per farlo funzionare.

SELECT NewStatHistory.* 
FROM NewStatHistory
INNER JOIN (
  SELECT MAX(DateEntered) entered, statID, DateApplies
  FROM NewStatHistory
  WHERE StatID = @statID 
    AND campusID = @campusID
    AND IsTarget = 0
  GROUP BY DateApplies, statID
) summary 
ON summary.entered = newstathistory.dateEntered AND
  summary.statID = newStatHistory.statID AND 
  summary.DateApplies = newStatHistory.DateApplies
WHERE NewStatHistory.StatID = @statID AND
  IsTarget = 0 AND
  campusID = @campusID
ORDER BY NewStatHistory.DateApplies DESC

Qualcuno ha qualche idea su come farlo funzionare. Altrimenti, dovrò trovare un altro db incorporato da usare. Oltre a questa query, SQLite ha fatto tutto ciò che gli ho chiesto.

Per quanto riguarda gli indici, su SqlServer ho solo la chiave primaria indicizzata. Su SQLite, ho provato solo con la chiave primaria, ma poi ho aggiunto su diverse altre colonne senza risultati.

La sottoquery viene eseguita in pochissimo tempo anche su SQLite, quindi sembra essere il join che causa il rallentamento.

È stato utile?

Soluzione 2

Ho scoperto che in realtà è specificato nella documentazione che questo tipo di join non è ben supportato. Il modo per aggirare il problema consiste nell'utilizzare un'altra tabella anziché una query secondaria. Quindi è tornato ad essere incredibilmente veloce.

Altri suggerimenti

L'esecuzione di EXPLAIN QUERY PLAN sulla tua query suggerisce che sta eseguendo 2 scansioni di tabelle per questa query.

Potresti voler leggere la pagina La panoramica dello Strumento per ottimizzare le query SQLite per ulteriori informazioni su come funziona l'ottimizzatore

qualcosa di simile a questo può aiutare (non testato, oltre a vederlo in uso):

CREATE INDEX foo ON NewStatHistory(statID, campusID, IsTarget, DateApplies);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top