为什么查询给出不正确的结果?

时间:2014-01-22 00:43:06

标签: mysql sql

美好的一天。

表中有数据:

id UserIdn CommentIdn LikeIdn NewsIdn Type IsFavorite DateCreate

1  527464             613895  748153  up   yes   0000-00-00 00:00:00

对于获取计数值,我使用代码:

SELECT 
count(Type='up') as CountUp, 
count(Type='down') as CountDown 
FROM Likes WHERE NewsIdn = '748153'

但结果是

CountUp  CountDown
   1       0

我得到了

CountUp  CountDown
    1       1

请告诉我为什么我的结果不正确?如何查询是对的?

3 个答案:

答案 0 :(得分:1)

在sum()中尝试使用案例。

SELECT SUM(CASE WHEN Type = 'up' THEN 1 ELSE 0 END) as 'count_up'
...

答案 1 :(得分:1)

例如Type='up'函数中的COUNT()为false(0)或true(1)。但COUNT()并不关心这一点,只是看到有一排。请改用SUM()

SELECT 
COALESCE(SUM(Type='up'), 0) as CountUp, 
COALESCE(SUM(Type='down'), 0) as CountDown 
FROM Likes WHERE NewsIdn = '748153'

答案 2 :(得分:0)

试试这个......

SELECT
SUM(CASE WHEN Type='up' AND Type IS NOT NULL THEN 1 ELSE 0 END) as CountUp,
SUM(CASE WHEN Type='down' AND Type IS NOT NULL THEN 1 ELSE 0 END) as CountDown
FROM Likes
WHERE NewsIdn = '748153'