[英]SQL result missing a piece
I'll get straight to the point.我将进入正题。 I've 2 tabels:
我有 2 个表:
1) poll_options 1) 轮询选项
| (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 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
.链接在一起的是
ID
从poll_options
与poll_options_ID
从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.它只显示投票的
poll_options
的name
。 I would like to show all the name
of poll_options
and the ones where there is no vote yet, make them show 0.我想显示
poll_options
所有name
以及尚未投票的名称,使它们显示为 0。
for example (with current sql and woning_id=20):例如(使用当前的 sql 和 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?我可以使用 SQL 中的某些内容来获得此结果吗?
Your SQL is invalid, but it would work if you inserted and
:您的 SQL 无效,但如果您插入
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.也就是说,您应该将
$woning_id
作为参数传递到查询中。 Don't munge query strings with such values -- they can cause unexpected and hard to find errors.不要用这样的值来处理查询字符串——它们可能会导致意外且难以发现的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.