详细描述如:http://blog.csdn.net/seven_cm/article/details/41527505
结果集只有1和0,为什么结果是不一样的?
楼主的误区是在 case status when status>0 then 1 else 0 end 上,正规的写法是 case status when 0 then 1 else 0 end 注意这里是没有 status>0的。
需要注意和区分CASE的两种语法的不同。
CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END
CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END
当使用了CASE value这种格式,则MYSQL会对 value 与后面的每个 compare_value 进行比较。
而楼主在语句中正是使用的 CASE value这种格式
所以当 case status when status>0 then 1 else 0 end 时,要意识到 when status>0 这里不是条件,是值。举例来说。比如第一条记录
+-----+-----+--------+
| uid | tid | status |
+-----+-----+--------+
| 1 | 1 | 0 |
这条件中 status=0 则 case status when status>0 then 1 else 0 end
被处理为 case 0 when 0>0 then 1 else 0 end,
而0>0 逻辑运算的结果是 false 为 0 ,
所以语句为 case 0 when 0 then 1 else 0 end
这样运算的结果为 1
其实看一下这个结果应该会更容易理解问题出在哪儿了。
mysql> select tid,status,status>0 v1,status>=0 v2,
-> case status when status>0 then 1 else 0 end as c1,
-> case status when status>=0 then 1 else 0 end as c2
-> from case_test;
+-----+--------+------+------+------+------+
| tid | status | v1 | v2 | c1 | c2 |
+-----+--------+------+------+------+------+
| 1 | 0 | 0 | 1 | 1 | 0 |
| 2 | 0 | 0 | 1 | 1 | 0 |
| 3 | 0 | 0 | 1 | 1 | 0 |
| 4 | 0 | 0 | 1 | 1 | 0 |
| 5 | 0 | 0 | 1 | 1 | 0 |
| 6 | 0 | 0 | 1 | 1 | 0 |
| 7 | 0 | 0 | 1 | 1 | 0 |
| 8 | 0 | 0 | 1 | 1 | 0 |
| 9 | 0 | 0 | 1 | 1 | 0 |
| 10 | 0 | 0 | 1 | 1 | 0 |
| 11 | 1 | 1 | 1 | 1 | 1 |
| 12 | 1 | 1 | 1 | 1 | 1 |
| 13 | 1 | 1 | 1 | 1 | 1 |
| 14 | 1 | 1 | 1 | 1 | 1 |
| 15 | 1 | 1 | 1 | 1 | 1 |
| 16 | 1 | 1 | 1 | 1 | 1 |
| 17 | 1 | 1 | 1 | 1 | 1 |
| 18 | 1 | 1 | 1 | 1 | 1 |
| 19 | 1 | 1 | 1 | 1 | 1 |
| 20 | 1 | 1 | 1 | 1 | 1 |
+-----+--------+------+------+------+------+
20 rows in set (0.02 sec)
mysql>
这不是很简单么
如果是>=0,那么有20个,如果是>0,有10个。
你把values的第三个值数一下就知道了。
status>0: 只包括status比0大的记录
status>=0: 包括status比0大的记录,**_同时包括status=0的记录_**
这不是高手的问题,这是小学生的问题。两个要一样的话,那后面的那个等于号是干什么的呢?
select uid,sum(case status when 1 then 1 else 0 end) friend,sum(case status when status>=0 then 1 else 0 end) concern
from case_test group by uid;
结果如下:
+-----+--------+---------+
| uid | friend | concern |
+-----+--------+---------+
| 1 | 10 | 10 |
+-----+--------+---------+
select uid,sum(case status when 1 then 1 else 0 end) friend,sum(case status when status>0 then 1 else 0 end) concern
from case_test group by uid;
结果如下:
+-----+--------+---------+
| uid | friend | concern |
+-----+--------+---------+
| 1 | 10 | 20 |
+-----+--------+---------+
你的查询语句的写法和你想得到的结果不一致。
case status when status>=0 then 1 else 0 end,这句的意思是判断status的值与status>=0的值来比较,注意是与status>=0的值比较,不是与status本身的值比较。要获取你希望的结果,查询语句的写法应该是
SELECT uid
, SUM(
CASE status
WHEN 1 THEN 1
ELSE 0
END
) AS friend
,SUM(
CASE
WHEN status>=0 THEN 1
ELSE 0
END
) AS concern
FROM case_test
GROUP BY uid;
同理,关于status>0的写法也参照上面的写法修改。
关于MYSQL CASE的不同写法,可以参考MYSQL函数-控制流程函数中的CASE WHEN THEN 函数。如果还有不明白的,可以提出来。