Find the count of EMPTY or NULL columns in a MySQL table

前端 未结 4 1939
慢半拍i
慢半拍i 2021-01-21 20:04

I have around 30 columns in a MySQL table. I want to calculate how many column fields for a particular row are empty. This table is for storing user information. I want to fin

4条回答
  •  温柔的废话
    2021-01-21 21:00

    As I understand it you have a table such as

    id | FName | LName  | Age
    1  | John  | ""     | NULL
    2  | Mary  | Simons | NULL
    

    And you want: row 1 has 2 empty/null fields, and row 2 has 1 empty/null fields

    SELECT
        id,
    
        IF (FName IS NULL OR FName = '', 1, 0) + 
        IF (LName IS NULL OR LName = '', 1, 0) + 
        IF (Age IS NULL OR Age = '', 1, 0)
        as empty_field_count
    

    Though now that I've written this I see Saul's response, I think that may have better performance that this solution.

提交回复
热议问题