[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: SQL: incrementare valore



On 30/04/17 08:41, Paolo Redaelli wrote:
Il 29/04/2017 22:49, Alessandro Pellizzari ha scritto:
On 29/04/17 14:10, Giuliano Curti wrote:

UPDATE mee SET r_co = (SELECT max(r_co) FROM mee) + r_to - r_fr WHERE
r_id =
la funzione UPDATE itera su tutti i record, la funzione SELECT
nidificata, che anch'essa itera su tutti i record, non risulta
penalizzante? si avrebbe un algoritmo di complessità N**2;
Questo vale solo se non hai indici sul DB.
Perdonatemi se mi intrometto, ma una bella EXPLAIN non risolverebbe
tutti i nostri dubbi?


Non ch'io abbia dei dubbi, almeno su di PostgreSQL ma per curiosità ho creato una tabella come segue:

create table test (id serial, a integer, b integer);

e dopo aver inserito qualche riga ho ottenuto:

explain verbose update test set a = (select max(a) from test) - b where id = 1;

 Update on public.test  (cost=35.51..71.03 rows=10 width=18)
   InitPlan 1 (returns $0)
     ->  Aggregate  (cost=35.50..35.51 rows=1 width=4)
           Output: max(test_1.a)
-> Seq Scan on public.test test_1 (cost=0.00..30.40 rows=2040 width=4)
                 Output: test_1.id, test_1.a, test_1.b
   ->  Seq Scan on public.test  (cost=0.00..35.52 rows=10 width=18)
         Output: test.id, ($0 - test.b), test.b, test.ctid
         Filter: (test.id = 1)

dove si vede chiaramente che la subquery viene eseguita solo una volta ed il risultato memorizzato in $0.

Ciao,

federico

--
Federico Di Gregorio                         federico.digregorio@dndg.it
DNDG srl                                                  http://dndg.it
  Qu'est ce que la folie? Juste un sentiment de liberté si
   fort qu'on en oublie ce qui nous rattache au monde... -- J. de Loctra


Reply to: