有没有办法将查询应用于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
答案 0 :(得分: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'
然后运行此查询的输出。
<强>更新强>
这是将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 :(得分:0)
如果表格与任何字段相关,则可以使用
等表格的别名select count(*) from table1 tb1, table2 tb2, table3 tb3 where
tb1.field1 = tb2.field2 and tb2.field2 = tb3.field3
与之相似,
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子句。
输出:
| count1 | count2 |共3个记录|
| 50 | 36 | 21 |