2011-12-06 42 views
5

有沒有辦法將查詢應用到mysql數據庫中的每個表格?將mysql查詢應用到數據庫中的每個表格

喜歡的東西

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

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

回答

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

提防這只是一個近似值

爲了刪除所有的表,你可以不喜歡的內容這

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

然後運行此查詢的輸出。

UPDATE。

這是應用truncate table所有表中的一個特定數據庫

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

啊..謝謝。來自@str的準備工作非常有用。 – scravy

+0

您更新的程序非常有用。它看起來像'db_name'不會影響任何東西,儘管當前的設置(我完全刪除它在程序中沒有問題)。 – DACrosby

+0

不錯。要顯示每個表中的條目個數:select table_name,table_rows from information_schema.tables where table_schema = 'your_db_name' gaoithe

0

如果表是由您可以使用表的別名一樣

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

任何領域相關的存儲過程similary,

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

您可以根據您的要求包含條件。

如果表有那麼沒有關係,使用下面

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 

你可以刪除where子句,如果沒有條件。

OUTPUT:

| COUNT1 | count2 |共3個記錄|

| 50 | 36 | 21 |

相關問題