SQL结果缺少一块

时间:2018-04-10 18:23:42

标签: sql mysqli

我会直言不讳。 我有2个表格:

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      |

ID poll_optionspoll_options_ID的{​​{1}}联系起来poll_votes。我在它们周围放置了( )以使其成为可视化的。

我已经查询了每个答案的总票数。

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的{​​{1}}投票。 我想展示poll_options name以及尚未投票的所有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中的某些东西来获得此结果吗?

1 个答案:

答案 0 :(得分:1)

您的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作为参数传递给查询。不要使用这些值来查询字符串 - 它们可能会导致意外且很难找到错误。