Why do I need “OR NULL” in MySQL when counting rows with a condition

前端 未结 5 678
小蘑菇
小蘑菇 2020-11-30 14:08

There is a question about MySQL\'s COUNT() aggregate function that keeps popping into my head time to time. I would like to get some explanation to why it is working the way

5条回答
  •  我在风中等你
    2020-11-30 14:58

    COUNT(expression) counts the number of rows for which the expression is not NULL. The expression value=4 is only NULL if value is NULL, otherwise it is either TRUE (1) or FALSE (0), both of which are counted.

    1 = 4         | FALSE
    4 = 4         | TRUE
    1 = 4 OR NULL | NULL
    4 = 4 OR NULL | TRUE
    

    You could use SUM instead:

    SELECT SUM(value=4) FROM test
    

    This is not particularly useful in your specific example but it can be useful if you want to count rows satisfying multiple different predicates using a single table scan such as in the following query:

    SELECT
        SUM(a>b) AS foo,
        SUM(b>c) AS bar,
        COUNT(*) AS total_rows
    FROM test
    

提交回复
热议问题