检查sql中有多少列不是NULL

时间:2015-01-01 23:54:57

标签: mysql sql

正如标题所说

enter image description here

所以在这个例子中,我会从第一行获得2,从第二行获得1。

$sql = "SELECT Passive, Q, W, E, R FROM champions WHERE Passive, Q, W, E, R IS NOT NULL AND Patch_No ='".$_GET['Patch_No']."' AND Champion = ".$row['champion']."";
$result = $conn->query($sql);
$rows = $result->num_rows;

编辑代码的大部分我试图弄清楚没有错误出现,虽然这个回声似乎没有显示我想要的数字

if($result = $conn->query($sql)){
    $champ_number = $result->num_rows;
    $i = 1;
    $champion = array();
    $noofspellschamp = array();
    while($row = $result->fetch_assoc()){

        $champion[$i]=$row['champion'];

        $sql2 = "
        SELECT Passive, Q, W, E, R,
                ((Passive is not null) + (Q is not null) + (W is not null) + (E is not null) + (R is not null)
                ) as NumNotNull
        FROM champions
        WHERE Patch_No ='".$_GET['Patch_No']."' AND
              Champion = ".$row['champion']."";
        $result2 = $conn->query($sql2);
        echo $result2;
        $noofspellschamp[$i] = $result2;                            

        $i+=1;
        //echo $champion[count($row)];
    }

1 个答案:

答案 0 :(得分:0)

这是一种方法:

SELECT Passive, Q, W, E, R,
      ((Passive is not null) + (Q is not null) + (W is not null) + (E is not null) + (R is not null)
      ) as NumNotNull
FROM champions
WHERE Patch_No ='".$_GET['Patch_No']."' AND
      Champion = $row['champion'];

MySQL将布尔值 - 在数字上下文中 - 视为数字,其中1为真,0为假。您可以将这些值一起添加以获得所需的计数。

我删除了where子句中的第一个表达式;它在语法上是不正确的,我不确定它的目的是什么。