I am building a simple poll system and part of this is a query to pull the poll results from a MySQL table.
The system contains 3 tables.
pollquestions - Contains just an id and question string.
polloptions - stores options for each question. contains id, questionid and a string for the option
pollanswers - contains the 'votes' cast in each poll. Contains and id, question id and option id.
To get the results data for a poll I'm using the following simple query which seems to work OK. (in this case I am grabbing the results for poll '2')
This is fine and returns what I need, but if possible I would also like to be able to add up the total number of votes cast. i.e. The sum of the 'votes' column.
I'm having trouble doing this as if I try to use SUM(votes) the column isn't recognised (I guess because it's an alias) and if I use SUM(COUNT(*)) I get an error about the Invalid use of GROUP function.
I know this has to be simple!
BTW, yes I could do this via PHP but I am trying to improve my knowledge of MySQL so this would be nice to know.
Many thanks.
Incidentally, I am using MySQL 4
<honk>*:O)</honk>
Tyres: Mine's a pint of the black stuff.
Mike: You can't drink a pint of Bovril.
The system contains 3 tables.
pollquestions - Contains just an id and question string.
polloptions - stores options for each question. contains id, questionid and a string for the option
pollanswers - contains the 'votes' cast in each poll. Contains and id, question id and option id.
To get the results data for a poll I'm using the following simple query which seems to work OK. (in this case I am grabbing the results for poll '2')
Code:
SELECT
COUNT(*) as votes,
polloptions.id,
polloptions.option
FROM pollanswers
LEFT JOIN polloptions ON polloptions.id=pollanswers.answerid
WHERE pollanswers.questionid=2
GROUP BY pollanswers.answerid
This is fine and returns what I need, but if possible I would also like to be able to add up the total number of votes cast. i.e. The sum of the 'votes' column.
I'm having trouble doing this as if I try to use SUM(votes) the column isn't recognised (I guess because it's an alias) and if I use SUM(COUNT(*)) I get an error about the Invalid use of GROUP function.
I know this has to be simple!
BTW, yes I could do this via PHP but I am trying to improve my knowledge of MySQL so this would be nice to know.
Many thanks.
Incidentally, I am using MySQL 4
<honk>*:O)</honk>
Tyres: Mine's a pint of the black stuff.
Mike: You can't drink a pint of Bovril.