[英]SQL result missing a piece
我將進入正題。 我有 2 個表:
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
| 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_options
與poll_options_ID
從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
這就是我的問題所在。 它只顯示投票的poll_options
的name
。 我想顯示poll_options
所有name
以及尚未投票的名稱,使它們顯示為 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 中的某些內容來獲得此結果嗎?
您的 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
作為參數傳遞到查詢中。 不要用這樣的值來處理查詢字符串——它們可能會導致意外且難以發現的錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.