我会直截了当地说出来。我有两个桌子:
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 |将它们连接在一起的是来自poll_options的poll_options和来自poll_votes的poll_options_ID。我把( )放在它们周围,以使其具有视觉效果。
我提出了一个查询,以显示每个答案的总票数。
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这就是我的问题所在。它只显示有投票权的来自name的poll_options。我想展示所有的name of poll_options和那些还没有投票的,让它们显示0。
例如(使用当前的sql和woning_id=20):
| answer |total_votes_per_answer|
| 0-5 | 1 |
| 5-10 | 1 |我想要的是:
| 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 |SQL中有什么可以用来获得这个结果的吗?
发布于 2018-04-10 18:25:51
您的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;也就是说,您应该将$woning_id作为参数传递到查询中。不要用这样的值来处理查询字符串--它们可能会导致意外的,并且很难找到错误。
https://stackoverflow.com/questions/49760589
复制相似问题