使用PHP计算空列Mysql

时间:2013-10-04 20:10:28

标签: php mysql

我想要计算空列或具有特定值

    $q = mysql_query("
        SELECT SUM(
            (`foto` = 'avatar_small.png') +
            (`email` IS NULL) + 
            (`cidade` IS NULL) + 
            (`estado` IS NULL) + 
            (`endereco` IS NULL) + 
            (`numero` IS NULL) + 
            (`cep` IS NULL) + 
            (`telefone` IS NULL)
        ) FROM `info_complementos` WHERE id_user = ".$_SESSION['usuario_cargo']) or die(mysql_error());

    $retorno = mysql_num_rows($q);  

    return $retorno[0];
问题是它显示了结果

1 个答案:

答案 0 :(得分:0)

您可以使用mysql中的COUNT函数来计算返回的行数。因此,您希望过滤掉WHERE子句中不需要的行。这将计算符合所有条件的所有行。如果要匹配包含某些NULL值的行,可以将AND更改为OR

<?php
$q = mysql_query("
SELECT COUNT(*) FROM `info_complementos` 
WHERE 
      id_user = $_SESSION['usuario_cargo'] AND
      `foto` = 'avatar_small.png' AND
      `email` IS NULL AND
      `cidade` IS NULL) AND
      `estado` IS NULL) AND
      `endereco` IS NULL AND 
      `numero` IS NULL AND 
      `cep` IS NULL AND
      `telefone` IS NULL");

$result = mysql_fetch_array($q);
echo $result[0];

希望这有帮助。