Thursday, 30 August 2018

Mysql Query does not summarize multiple records, only takes the first record

We have a table (survey) which has different survey questions. Each survey_id only appears once in this table.

We have a table of votes (vote_survey_table), which logs the user votes for each survey question. The table has fields for survey_id, vote_yes, vote_no, user_id, etc. This table has more than one entry for each survey_id.
I'm trying to query the vote table to add up all the votes for a given survey question, but the query I'm coming up with only adds up the first instance of the row int he vote table.
SELECT survey.survey_id, vote_survey_table.vote_yes AS cnt,
survey.survey_name, survey.survey_details
FROM survey
LEFT JOIN vote_survey_table AS votedb ON vote_survey_table.vote_survey_id = survey.survey_id
GROUP BY survey.survey_id
ORDER BY cnt DESC, survey.survey_id LIMIT 0,5

What am I missing on this query that should tell the query to add up all the instances of a survey_id in the vote table and sum up the result? I tried changing the LEFT JOIN to an INNER JOIN, but this didn't do the trick either.
Thanks in advance as always.

You need to sum the votes.
SELECT survey.survey_id, SUM(vote_survey_table.vote_yes) AS cnt,
       survey.survey_name, survey.survey_details
FROM survey LEFT JOIN vote_survey_table AS votedb
              ON vote_survey_table.vote_survey_id = survey.survey_id
GROUP BY survey.survey_id, survey.survey_name, survey.survey_details
ORDER BY cnt DESC, survey.survey_id LIMIT 0,5

If vote_yes is a boolean field, then use COUNT instead of SUM.

0 comments:

Post a Comment