Counting how many MySQL fields in a row are filled (or empty)

后端 未结 3 1960
被撕碎了的回忆
被撕碎了的回忆 2021-02-09 05:59

I need to put together a method that would allow me to quantify how many fields in a row have been filled by a user.

For example:

User    Name    Age             


        
相关标签:
3条回答
  • 2021-02-09 06:28
    $result = mysql_query('SELECT * FROM `MyTable`');
    while($row = mysql_fetch_row($result)){
        $empty_count = 0;
        $count = count($row);
        for($i = 0; $i < $count; $i++)
            if($row[$i] === '' || $row[$i] === 'NULL')
                $empty_count++;
        echo 'User '.$row[0].' = '.((int)(100*(1-$empty_count/($count-1)))).'% complete';
    }
    
    0 讨论(0)
  • 2021-02-09 06:38
    select 
        User,
        (
            case Name when '' then 0 else 1 end
            +
            case when Age is null then 0 else 1 end
            +
            case Country when '' then 0 else 1 end
            +
            case Gender when '' then 0 else 1 end
            +
            case when Height is null then 0 else 1 end
        ) * 100 / 5 as complete
    

    Use the case according to what no info means: empty or null.

    0 讨论(0)
  • 2021-02-09 06:51

    i think this would be better solved in php where you make a function that defines the column names and assigns a weight to each one and then calculatea the %complete based on the data retrieved from the db that why a name can count for 20% and an age can count for 5% etc. and the columns and weight definitions can even be stored externally in say an xml file so someone else can play with percentages and dont need a programmer to tweak the requirements

    0 讨论(0)
提交回复
热议问题