2011-12-06 20 views
5

esiste un modo per applicare una query a ciascuna tabella in un database mysql?Applicare query mysql a ciascuna tabella in un database

Qualcosa di simile

SELECT count(*) FROM {ALL TABLES} 
-- gives the number of count(*) in each Table 

e

DELETE FROM {ALL TABLES} 
-- Like DELETE FROM TABLE applied on each Table 

risposta

11
select sum(table_rows) as total_rows 
from information_schema.tables 
where table_schema = 'your_db_name' 

attenzione questo è solo un valore approssimativo

Per cancellare il contenuto di tutte le tabelle si può fare qualcosa di simile questo

select concat('truncate ',table_name,';') 
from information_schema.tables 
where table_schema = 'your_db_name' 

Quindi eseguire l'output di questa query.

AGGIORNAMENTO.

Si tratta di una stored procedure da applicare truncate table a tutte le tabelle di un database specifico

delimiter // 
drop procedure if exists delete_contents // 
create procedure delete_contents (in db_name varchar(100)) 
begin 
declare finish int default 0; 
declare tab varchar(100); 
declare cur_tables cursor for select table_name from information_schema.tables where table_schema = db_name and table_type = 'base table'; 
declare continue handler for not found set finish = 1; 
open cur_tables; 
my_loop:loop 
fetch cur_tables into tab; 
if finish = 1 then 
leave my_loop; 
end if; 

set @str = concat('truncate ', tab); 
prepare stmt from @str; 
execute stmt; 
deallocate prepare stmt; 
end loop; 
close cur_tables; 
end; // 
delimiter ; 

call delete_contents('your_db_name'); 
+1

ah .. grazie. Il preparare stmt da @str è molto utile. – scravy

+0

La procedura aggiornata è molto utile. Sembra che 'db_name' non abbia effetto su nulla con la configurazione corrente (l'ho rimosso completamente senza problemi nella procedura). – DACrosby

+0

Bello. Per mostrare il conteggio individuale delle voci in ogni tabella: select table_name,table_rows from information_schema.tables where table_schema = 'your_db_name' gaoithe

0

se le tabelle sono correlate da tutto il campo è possibile utilizzare l'alias di tabelle come

select count(*) from table1 tb1, table2 tb2, table3 tb3 where 
tb1.field1 = tb2.field2 and tb2.field2 = tb3.field3 

similario,

delete from table1 tb1, table2 tb2, table3 tb3 where 
tb1.field1 = tb2.field2 and tb2.field2 = tb3.field3 

è possibile includere le condizioni secondo i requisiti dell'utente.

Se le tabelle non hanno alcuna relazione quindi utilizzare sotto

SELECT 
    (SELECT COUNT(*) FROM table1 WHERE someCondition) as count1, 
    (SELECT COUNT(*) FROM table2 WHERE someCondition) as count2, 
    (SELECT COUNT(*) FROM table3 WHERE someCondition) as count3 

è possibile rimuovere la clausola in cui se non ci sono le condizioni.

USCITA:

| count1 | count2 | count3 |

| 50 | 36 | 21 |

Problemi correlati