I'm facing a problem in a data importation script in SQL(MySQL) where I need to GROUP rows by type to COUNT how much rows there are from each type. So far, it isn't really a problem, because I know that I can do:
SELECT
data.type,
COUNT(data.type)
FROM data
GROUP BY data.type;
So, by doing it, I have the result:
-------------- --------------------- | type | COUNT(data.type) | |--------------|---------------------| | 0 | 1 | | 1 | 46 | | 2 | 35 | | 3 | 423 | | 4 | 64 | | 5 | 36 | | 9 | 1 | -------------- ---------------------
I know that in the type column the values will always be in the range from 0 to 9, like the above result. So, I would like to list not only the existing values in the table content but the missing type values too, with their COUNT value set to 0.
Based on the above query result, the expected result would be:
-------------- --------------------- | type | COUNT(data.type) | |--------------|---------------------| | 0 | 1 | | 1 | 46 | | 2 | 35 | | 3 | 423 | | 4 | 64 | | 5 | 36 | | 6 | 0 | | 7 | 0 | | 8 | 0 | | 9 | 1 | -------------- ---------------------
I could trickly INSERT one row of each type before GROUP/COUNT-1 the table content, flagging some other column on INSERT to be able to DELETE these rows after. So, the steps of my importation script would change to:
- TRUNCATE table; (I can't securily import new content if there were old data in the table)
- INSERT "control" rows;
- LOAD DATA INFILE INTO TABLE;
- GROUP/COUNT-1 the table content;
- DELETE "control" rows; (So I can still work with the table content)
- Do any other jobs;
But, I was looking for a cleaner way to reach the expected result. If possible, a single query, without a bunch of JOINs.
I would appreciate any suggestion or advice. Thank you very much!
EDIT
I would like to thank for the answers about CREATE a table to store all types to JOIN it. It really solves the problem. My approach solves it too, but does it storing the types, as you did.
So, I have "another" question, just a clarification, based on the received answers and my desired scope... is it possible to reach the expected result with some MySQL command that will not CREATE a new table and/or INSERT these types?
I don't see any problem, actually, in solve my question storing the types... I just would like to find a simplified command... something like a 'best practice'... some kind of filter... as I could run:
GROUP BY data.type(0,1,2,3,4,5,6,7,8,9)
and it could return these filtered values.
I am really interested to learn such a command, if it really exists/is possible.
And again, thank you very much!