SQL查询:WHERE子句

时间:2011-10-08 20:06:29

标签: mysql sql

我的表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子句的问题?

2 个答案:

答案 0 :(得分:3)


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

像这样的东西

答案 1 :(得分:1)

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;