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

前端 未结 5 679
小蘑菇
小蘑菇 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 15:05

    This should reveal all

    SELECT 4=4, 3=4, 1 or null, 0 or null
    

    Output

    1   |   0   |   1   |   NULL
    

    Facts

    1. COUNT adds up the columns / expressions that evaluate to NOT NULL. Anything will increment by 1, as long as it is not null. Exception is COUNT(DISTINCT) where it increments only if it is not already counted.

    2. When a BOOLEAN expression is used on its own, it returns either 1 or 0.

    3. When a boolean is OR-ed with NULL, it is NULL only when it is 0 (false)

    To others

    Yes if the count is the ONLY column desired, one could use WHERE value=4 but if it is a query that wants to count the 4's as well as retrieving other counts/aggregates, then the filter doesn't work. An alternative would have been SUM(value=4), e.g.

    SELECT sum(value=4)
      FROM test
    

提交回复
热议问题