Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it L'avatar di nicola75ss
    Registrato dal
    Nov 2004
    Messaggi
    12,922

    [mysql] - prepared statement e mancata interpretazione query dinamica

    Ciao a tutti. Ho un problema con una query dinamica che genero tramite information schema e che non viene parsata dalla prepared statement.
    Posto un dump per riprodurre il problema.

    codice:
    create database if not exists nick;
    
    use nick;
    
    create table t1(
    id int not null auto_increment,
    campo int,
    primary key (id)
    );
    
    insert into t1 (campo) values (10),(20);
    
    create table t2(
    id int not null auto_increment,
    altrocampo int,
    campo int,
    primary key (id)
    );
    
    insert into t2 (altrocampo,campo) values (1,50),(2,50);
    
    
    create table t3 (
    id int not null auto_increment,
    pippo int,
    primary key (id)
    );
    
    insert into t3 (pippo) values (1),(2);
    L'obiettivo è quello di ottenere la somma del campo "campo" di tutte le tabelle in cui tale campo è presente, nello specifico quindi la somma di t1 (10+20) e t2 (50+50). t3 invece non contiene il campo.

    La query che realizza quanto desiderato è:

    codice:
    select (select sum(campo) from t1)+(select sum(campo) from t2);
    Veniamo al mio problema.
    Questa è la prepared statement che utilizzo:

    codice:
    prepare stmt from "select concat('select ',group_concat('(select sum(campo) from ',table_name,')' separator '+'),';')
    from information_schema.columns
    where table_schema = 'nick' and column_name = 'campo'";
    execute stmt;
    deallocate prepare stmt;
    Non riesco a capire perchè la query non venga parsata ma mi restituisca solo la stringa:

    codice:
    select (select sum(campo) from t1)+(select sum(campo) from t2);
    Dopo vari tentativi in questo modo invece ottengo il risultato desiderato:

    codice:
    set @str = (concat('select ',(select group_concat('(select sum(campo) from ',table_name,')' separator '+')
    from information_schema.columns
    where table_schema = 'nick' and column_name = 'campo'),';'));
    -- select @str;
    prepare stmt from @str;
    execute stmt;
    deallocate prepare stmt;
    Se decommentate la riga relativa alla select vedrete che la stringa generata è la stessa.
    Cos'è quindi che provoca la mancata interpretazione della query?
    Grazie per l'attenzione.

  2. #2
    Utente di HTML.it L'avatar di nicola75ss
    Registrato dal
    Nov 2004
    Messaggi
    12,922
    Ci riprovo.

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.