I'll get straight to the point. I've 2 tabels:
1) poll_options
| (ID) | Name |
| 1 | 0-5 |
| 2 | 5-10 |
| 3 | 10-15 |
| 4 | 15-20 |
| 5 | 20-25 |
| 6 | 25-30 |
| 7 | 30-35 |
| 8 | 35-40 |
| 9 | 40-45 |
| 10 | 45-50 |
| 11 | 50+ |
2) poll_votes
| ID | (poll_options_id) | vote_count | woning_id |
| 1 | 3 | 1 | 20 |
| 2 | 11 | 1 | 18 |
| 3 | 5 | 1 | 25 |
| 4 | 5 | 1 | 27 |
| 5 | 3 | 1 | 25 |
| 6 | 4 | 1 | 26 |
Linking them together is the ID
from poll_options
with poll_options_ID
from poll_votes
. I placed ( )
around them to make is visual.
I've made a query to show the total votes made for each answer.
SELECT o.name as answer, sum(v.vote_count) as total_votes_per_answer
FROM poll_options as o LEFT JOIN poll_votes as v ON v.poll_option_id = o.id
WHERE WONING_id='$woning_id'
GROUP BY o.name
ORDER BY o.id ASC
Here is where my problem is. It only shows the name
from poll_options
that have a vote. I would like to show all the name
of poll_options
and the ones where there is no vote yet, make them show 0.
for example (with current sql and woning_id=20):
| answer |total_votes_per_answer|
| 0-5 | 1 |
| 5-10 | 1 |
What I want it to be:
| answer |total_votes_per_answer|
| 0-5 | 1 |
| 5-10 | 1 |
| 10-15 | 0 |
| 15-20 | 0 |
| 20-25 | 0 |
| 25-30 | 0 |
| 30-35 | 0 |
| 35-40 | 0 |
| 40-45 | 0 |
| 45-50 | 0 |
| 50+ | 0 |
Is there something in SQL that I can use to get this result?
Your SQL is invalid, but it would work if you inserted and
:
SELECT o.name as answer, sum(v.vote_count) as total_votes_per_answer
FROM poll_options o LEFT JOIN
poll_votes v
ON v.poll_option_id = o.id AND WONING_id = '$woning_id'
GROUP BY o.name
ORDER BY o.id ASC;
That said, you should be passing $woning_id
as a parameter into the query. Don't munge query strings with such values -- they can cause unexpected and hard to find errors.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.