MySQL:计算具有条件值的行

时间:2016-02-28 14:59:29

标签: mysql sql

我想知道用户登录了多少以及他们失败了多少以及成功。

category列是varchar(ex程序员的愚蠢),而值只是1或0。

如果1成功,如果为0表示失败。

$loginForced = " SELECT
                    Count(categori) AS login,                       
                    Count(CASE WHEN categori = '1' THEN categori ELSE 0 END) AS success,                        
                    Count(CASE WHEN categori = '0' THEN categori ELSE 0 END) AS fail                        
                 FROM 
                    log
                 WHERE  email = '".$personal."' "; 

2 个答案:

答案 0 :(得分:3)

在条件中使用sum

$loginForced = "select count(`categori`) as `login`,                       
                       sum(`categori` = '1') as `success`,                        
                       sum(`categori` = '0') as `fail`                        
                from `log`
                where `email` = '".$personal."' "; 

答案 1 :(得分:1)

您可能只想跳过ELSE表达式中的CASE

SELECT Count(categori) AS login,                       
       Count(CASE WHEN categori = '1' THEN categori END) AS success,                        
       Count(CASE WHEN categori = '0' THEN categori END) AS fail                        
FROM log
WHERE  email = '".$personal."' "; 

COUNT会考虑所有非空值,因此使用ELSE 0基本上没有意义,因为0将像其他任何一样计算值。