'默认' 5个可能值中的结果中缺少值的值

时间:2015-04-18 20:28:33

标签: mysql

我想要以相当奇怪的方式从db获取内容时遇到一些麻烦。说我有下一张桌子

ID  |   Rating
229 |   3
229 |   2
229 |   4
229 |   2
240 |   3
233 |   1
233 |   4
233 |   1
233 |   5
229 |   4
240 |   4

我需要看起来像

229 |   0,2,1,2,0
233 |   1,1,0,0,2
240 |   0,1,1,0,0

基本上。评级在1到5之间变化。对于id没有的每个评级,我在第2列中需要0。因此对于id 229来说它是0,2,1,2,0,因为它没有5和1的评级,因为它没有5,1和0,因为没有5,2和1的评级。 目前我有查询

select object_id, group_concat(qty order by rating desc) as qties
from (
select object_id, rating, count(rating) qty
from wp_fb_ratings
group by rating, object_id
) n
group by object_id

它选择了我需要的东西,除了它没有“零填充”缺失评级的计数。可以做我想做的事吗?

2 个答案:

答案 0 :(得分:0)

你可以做到

SELECT id, GROUP_CONCAT(rating_count ORDER BY rating DESC) rating_count
  FROM
(
  SELECT l.id, l.rating, COUNT(r.rating) rating_count
    FROM
  (
    SELECT id, rating
      FROM
    (
      SELECT DISTINCT id 
        FROM wp_fb_ratings
    ) d CROSS JOIN
    (
      SELECT 1 rating UNION ALL
      SELECT 2 UNION ALL
      SELECT 3 UNION ALL
      SELECT 4 UNION ALL
      SELECT 5 
    ) a
  ) l LEFT JOIN wp_fb_ratings r
      ON l.id = r.id
     AND l.rating = r.rating
  GROUP BY l.id, l.rating
) q
 GROUP BY id

输出:

|  id | rating_count |
|-----|--------------|
| 229 |    0,2,1,2,0 |
| 233 |    1,1,0,0,2 |
| 240 |    0,1,1,0,0 |

这是 SQLFiddle 演示

答案 1 :(得分:0)

想出下一个查询

select ID, group_concat(COALESCE(cnt,0) order by Rating desc) as rating_count
from 
(select distinct ID, tu.Rating from wp_fb_ratings join (
select 1 Rating union all
select 2 union all
select 3 union all
select 4 union all
select 5 
) tu ) t1
left join (select ID, Rating, count(*) cnt from wp_fb_ratings 
group by ID, Rating) t2 using(ID, Rating) 
group by ID

在大约75k行的表上,执行需要0.5秒,而来自@peterm的查询占用时间超过8分钟。