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
2
Answers
Your union all attempt was close. You want to return the my_isp from each table.
The "Every derived table must have its own alias" error is telling you that when you select from or join a subquery, you need to give it an alias (
as somealias
or justsomealias
after the close paren).Additionally, you are misunderstanding COUNT; the expression you give to count is only tested to see if it is NULL, and count returns the number of non-nulls for each group; if you omit a
group by
clause, the group is all the rows. For this case, you want justcount(1)
but to also group by and select the my_isp.So:
It may be more efficient to count within each table and sum them instead:
Without touching on the issue of the correct organization of tables (or one table), you can specify that the error
is caused by the absence of a subquery name.
This is too simple a mistake to discuss)
Actually, the request can be like this.
fiddle