Solution 1: two queries
You should use a table that contains the necessary (correct) types of answers:
| id | answer | --------------- | 1 | a1 | | 2 | a2 | etc.
Then you can count the results that really exist in your table:
SELECT atype, COUNT( * ) cnt FROM answers JOIN mytable ON mytable.atype=answers.answer GROUP BY answers.answer;
(Replace mytable with the appropriate table name).
Of course, this will only return existing results. To count the null rows, you can look for answers that do not appear in your table:
SELECT answer, '0' AS cnt FROM answers WHERE answer NOT IN( SELECT DISTINCT answer FROM answers JOIN mytable WHERE answer=mytable.atype );
Here is an example.
Solution 2: counter table
Another way is to use a counter table:
| id | answer | cnt | --------------------- | 1 | a1 | 0 | | 2 | a2 | 0 | etc.
Then each time you want to count the results, do:
UPDATE answers SET cnt=0; UPDATE answers SET cnt= (SELECT cnt FROM ((SELECT answers.answer, COUNT(*) AS cnt FROM answers JOIN mytable ON answers.answer=myTable.aType GROUP BY answers.answer) AS tbl) WHERE answers.answer=tbl.answer) WHERE EXISTS (SELECT cnt FROM ((SELECT answers.answer, COUNT(*) AS cnt FROM answers JOIN mytable ON answers.answer=mytable.atype GROUP BY answers.answer) AS tbl) WHERE answers.answer=tbl.answer);
This will update the counter values ββin your answer table, and you can simply SELECT * FROM answers ORDER BY answer to get the result.
Be careful: I believe that the second version, although convenient, will take much more processing power than the first, because of all the necessary subqueries.
Here is an example (UPDATE statements are on the left side!)
Solution 3: Update after recording
The best and least productive hungry solution for such cases, in your opinion, is to create a counter table similar to the one that I described in # 2, but update the counter values ββwhile users answer questions , instead of recounting all records every time you want to know the score.
It is easy to do. Each time a question is answered correctly, increase the counter in the answers table:
UPDATE answers SET cnt=cnt+1 WHERE answers.answer='a1';
And again your request will be
SELECT * FROM answers ORDER BY answer;