COUNT(*) from multiple tables in MySQL

前端 未结 5 1154
旧时难觅i
旧时难觅i 2020-11-30 03:50

How do I go about selecting COUNT(*)s from multiple tables in MySQL?

Such as:

SELECT COUNT(*) AS table1Count FROM table1 WHERE someCondition
JOIN?? 
         


        
相关标签:
5条回答
  • 2020-11-30 04:02

    You can use UNION

      SELECT COUNT(*) FROM table1 WHERE someCondition
      UNION
      SELECT COUNT(*) FROM table2 WHERE someCondition
      UNION
      SELECT COUNT(*) FROM table3 WHERE someCondition
    
    0 讨论(0)
  • 2020-11-30 04:03

    Here is simple approach to get purely the row counts from multiple tables, if there are no conditions on specific tables.

    Note:

    For InnoDB this count is an approximation. However, for MyISAM the count is accurate.

    Quoted from the docs:

    The number of rows. Some storage engines, such as MyISAM, store the exact count. For other storage engines, such as InnoDB, this value is an approximation, and may vary from the actual value by as much as 40% to 50%. In such cases, use SELECT COUNT(*) to obtain an accurate count.

    Using the information_schema.tables table you can use:

    SELECT 
        table_name, 
        table_rows
    FROM 
        information_schema.tables
    WHERE
        table_name like 'my_table%';
    

    Output:

    table_name    table_rows
    my_table_1    0
    my_table_2    15
    my_table_3    30
    

    I'm posting this answer because I ran across this post in search of this method, which matches the title of the post. Hopefully will help someone in the future.

    0 讨论(0)
  • 2020-11-30 04:05

    You can do this with subqueries, e.g.:

    select (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count, 
           (SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count 
    
    0 讨论(0)
  • 2020-11-30 04:05

    Try changing to:

    SELECT 
        COUNT(table1.*) as t1,
        COUNT(table2.*) as t2,
        COUNT(table3.*) as t3 
    FROM table1 
        LEFT JOIN tabel2 ON condition
        LEFT JOIN tabel3 ON condition
    
    0 讨论(0)
  • 2020-11-30 04:24

    You can do it by using subqueries, one subquery for each tableCount :

    SELECT
      (SELECT COUNT(*) FROM table1 WHERE someCondition) as table1Count, 
      (SELECT COUNT(*) FROM table2 WHERE someCondition) as table2Count,
      (SELECT COUNT(*) FROM table3 WHERE someCondition) as table3Count
    
    0 讨论(0)
提交回复
热议问题