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

前端 未结 5 669
小蘑菇
小蘑菇 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

    COUNT() function accepts an argument, that is treated as NULL or NOT NULL. If it is NOT NULL - then it increments the value, and doesn't do anything otherwise.

    In your case expression value=4 is either TRUE or FALSE, obviously both true and false are not null, that is why you get 10.

    but I am interested in a COUNT(condition) based solution.

    The count-based solution will be always slower (much slower), because it will cause table fullscan and iterative comparison of each value.

提交回复
热议问题