Search code examples
sqlmysql

Get count of each email type from multiple tables


I have 15+ tables with emails. I need to count how many emails exist for each internet service provider, like GMAIL, VMG, MSFT, or Other.

Using the below query, I can get a count of the ISPs for one table:

SELECT COUNT(`my_isp`) AS 'COUNT', `my_isp` FROM `table1` GROUP BY `my_isp`

This will spit out something like this:

COUNT | my_isp
---------------
4000  | Gmail
---------------
2000  | MSFT
---------------
10000 | other
---------------
15000 | VMG
---------------

What I need to do is get a total count of the above per each table, and I have over 15 tables.

I'm honestly not exactly sure how to start this.

** EDIT **

All of the tables have the same format with the same columns. They all look like this:

EMAIL | PROPERTY | STATUS | MY_ISP | CREATED_DATE | OTHER_DATES

Some emails will exist in multiple tables. The PROPERTY of each table will be different, as well as the STATUS and Date columns (I did not list all of the date columns).

** EDIT 2 **

So I tried to use a UNION ALL like this:

select COUNT(`my_isp`) AS 'COUNT'
from (select count(t1.`my_isp`) from `table1` t1
    UNION ALL
    select count(t2.`my_isp`) from `table2` t2
   ) 

But I get the below error:

#1248 - Every derived table must have its own alias

Solution

  • Without touching on the issue of the correct organization of tables (or one table), you can specify that the error

    #1248 - Every derived table must have its own alias
    

    is caused by the absence of a subquery name.
    This is too simple a mistake to discuss)

    Actually, the request can be like this.

    select my_isp ,sum(cnt) AS total
    from (select my_isp,count(t1.`my_isp`) cnt from `table1` t1 group by my_isp
        UNION ALL
        select my_isp,count(t2.`my_isp`) cnt from `table2` t2 group by my_isp
       ) subquery_name
    group by my_isp
    
    my_isp total
    google 3
    yahoo 2
    other 1

    fiddle