[英]SQL query: WHERE clause
我的表rating
具有以下結構:
RATING (INT 'id', INT 'stars') primary key 'id';
眾所周知, stars
價值只有1到5。
以下是我桌子的一些可能內容:
樣本表1:
ID Stars
-- -----
1 5
2 4
3 4
4 4
5 5
6 4
7 4
樣本表2:
ID Stars
-- -----
1 1
2 2
3 3
4 2
5 1
6 1
7 1
8 2
9 1
我使用以下查詢查詢我的表:
SELECT stars, count(stars) as count
FROM rating
GROUP BY stars
ORDER BY stars desc;
示例表1輸出:
stars count
----- -----
5 2
4 5
樣本表2輸出:
stars count
----- -----
3 1
2 3
1 5
我的問題:我想要這樣一個查詢,其中輸出顯示為ZERO表中沒有的值,即
對於Sample table1,我希望輸出如下:
stars count
----- -----
5 2
4 5
3 0
2 0
1 0
對於Sample Table2,我希望輸出如下:
stars count
----- -----
5 0
4 0
3 1
2 3
1 5
請注意,眾所周知, stars
值只有1到5。
我正在嘗試的查詢是(不正常):
SELECT stars, count(stars) as count
FROM rating
WHERE stars in (1,2,3,4,5)
GROUP BY stars
ORDER BY stars desc;
是where子句的問題?
select s.stars, count(r.stars) as count
from
(
select 1 as stars
union all select 2
union all select 3
union all select 4
union all select 5
) s
left join rating r on s.stars = r.stars
group by s.stars
order by s.stars desc
像這樣的東西
SELECT s.id, count(r.stars) as starcount
FROM rating r
RIGHT JOIN (SELECT 1 as id UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) s
ON (s.id = r.stars)
GROUP BY s.id
ORDER BY s.id desc;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.