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

时间:2013-12-10 21:30:55

标签: php mysql

我正试图通过存储在我的主要'电影'表中的外键来拉出我的演员列表。如果填充了所有actor字段,它将起作用,但如果其中任何一个字段为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");

最好的办法是什么?

干杯,

萨姆

2 个答案:

答案 0 :(得分:1)

$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 )

答案 1 :(得分:0)

使用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)
")