PHP -在SQL选择查询中忽略NULL

atmip9wb  于 2022-12-10  发布在  PHP
关注(0)|答案(2)|浏览(119)

我试图通过存储在主表“movies”中的外键来获取演员列表。如果所有演员字段都被填充,它将工作,但如果这些字段中的任何一个为NULL,它将死亡。

$stars = mysql_query("
    SELECT actor_name
    FROM actors
    WHERE actorID = $row[5] OR actorID = $row[6] OR actorID = $row[7] OR actorID = $row[8]  OR actorID = $row[9] OR actorID = $row[10]
")
or die("<h1>Error - (stars) the query could not be executed</h1>\n");
$count = 0;
while ($row_stars = mysql_fetch_array($stars)) {
    print("$row_stars[0]<br/>\n");
    if ($count == 2) {
        print("</td>\n");
        print("<td>\n");
    }
    $count++;
}
print("</td>\n </tr>\n");

最好的处理方法是什么?

3htmauhk

3htmauhk1#

$actors = array_slice($row, 2, 6);
$actors_without_nulls = array_filter($actors, 'strlen');
$actorIds = implode(', ', $actors_without_nulls);

现在试试看

SELECT actor_name
FROM actors
WHERE actorID IN ( actorIds )
li9yvcax

li9yvcax2#

使用MySQL COALESCE() function

$stars = mysql_query("
    SELECT actor_name
    FROM actors
    WHERE actorID = COALESCE($row[5],$row[6],$row[7],$row[8],$row[9],$row[10],-1)
")

相关问题