Apply mysql query to each table in a database

后端 未结 2 1461
一个人的身影
一个人的身影 2021-01-18 09:37

is there a way to apply a query to each table in a mysql database?

Something like

SELECT count(*) FROM {ALL TABLES}
-- gives the number of count(*) i         


        
2条回答
  •  甜味超标
    2021-01-18 09:58

    if tables are related by any field you can use alias of tables like

    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
    

    you can include conditions as per you requirements.

    If tables have no relation then use below

    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
    

    you can remove where clause if there is no conditions.

    OUTPUT:

    |count1 | count2 | count3|

    |50 |36 |21 |

提交回复
热议问题