按条件联合SQL请求:丢失行?工会失败?

时间:2015-05-23 03:28:27

标签: sql pdo

我试图将产品评论分类到图表中。为了总结结果,我将结果集分成四个卡盘:

Score >= 4.5
Score < 4.5 && Score >= 4
Score < 4 && Score >= 3
Score < 3

SQL请求如下所示:

SELECT DISTINCT COUNT(*) AS cnt
    FROM reviews 
    WHERE score >= 4.5
    AND id = 4 
    AND live = '1'
UNION
SELECT DISTINCT COUNT(*) AS cnt
    FROM reviews 
    WHERE score >= 4 
    AND score < 4.5
    AND id = 4 
    AND live = '1'
UNION
SELECT DISTINCT COUNT(*) AS cnt
    FROM reviews
    WHERE score >= 3
    AND score < 4
    AND id = 4 
    AND live = '1'
UNION
SELECT DISTINCT COUNT(*) AS cnt
    FROM reviews 
    WHERE score < 3
    AND id = 4 
    AND live = '1'

然后将其放入数组中。我注意到上面的请求返回十三行,或者计数总和等于13.我得到以下结果:

  

10
  2
  1

执行以下请求...

SELECT score
    FROM reviews
    WHERE live = '1'
    AND id = 4

...返回十四行。我想也许结果集可能会导致问题,但我没有看到任何问题。分数集如下:

  

5.0,5.0,5.0,5.0,4.9,4.9,4.9
  4.8,4.8,4.7,4.4,4.2,3.4,2.6

我不确定为什么单行丢失,任何想法,也许我的语法不稳定?为什么最终的联合(score < 3)什么都不返回?

2 个答案:

答案 0 :(得分:2)

请注意,最后两个查询都返回1,并且由于UNION删除了重复项,10 2 1 1 - &gt; 10 2 1。使用UNION ALL(请参阅What is the difference between UNION and UNION ALL?)。

答案 1 :(得分:1)

或者,跳过UNION,而不是使用CASE进行条件计数:

SELECT COUNT(case when Score >= 4.5 then 1 end) AS score_gt_4p5,
       COUNT(case when Score < 4.5 AND Score >= 4 then 1 end) AS score_4_to_4p5,
       COUNT(case when Score < 4   AND Score >= 3 then 1 end) AS score_3_to_4,
       COUNT(case when Score < 3 then 1 end) AS score_lt_3
FROM reviews
WHERE id = 4
  AND live = '1'

这样表只能读一次!