我有一个类似这样的查询:
$stmt = $db->prepare("SELECT location.id FROM location WHERE location.city = :city AND location.country = :country");
$stmt->execute(array(':city' => $cityVar, ':country' => $countryVar));
$locationID = $stmt->fetchColumn();
我遇到了一个问题,因为在数据库中,空的
city
列有时是null,有时是空字符串(我知道这是不正确的,但无法更改)。当我的$cityVar
变量为空时,我需要获取所有具有所需country
的条目,但现在我只能获取那些city
列为空字符串的条目(我无法获取那些city
为null的条目)。我唯一想到的解决办法是修改查询本身,例如:
$sql = "SELECT location.id FROM location WHERE location.country = :country ";
if ($cityVar) {
$sql .= "AND location.city = :city ";
}
但我想知道是否有更正当的方法来解决这个问题。注意:我需要搜索类似于city
的更多列。
WHERE COALESCE(location.city, "") = :city
吗? - Mindaugas Jakubauskas