gpt4 book ai didi

sql - PostgreSql 删除 null 和空字符串之间的差异

转载 作者:行者123 更新时间:2023-11-29 11:58:38 25 4
gpt4 key购买 nike

我有这样的查询:

$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 列有时为空,有时为空字符串(我知道这是错误的,但无法更改)。当我的 $cityVar 变量为空时,我需要获取所有包含所需 country 的条目,但现在我只获取那些 city 列为空的条目字符串(我没有得到那些 city 为 null 的字符串)。

我想到的唯一解决方案是修改查询本身,例如:

$sql = "SELECT location.id FROM location WHERE location.country = :country ";
if ($cityVar) {
$sql .= "AND location.city = :city ";
}

但我想知道是否有更多合法的方法来解决这个问题。注意:还有更多列,如 city 我需要搜索。

最佳答案

使用 COALESCE(city, '') - 它会将 NULL 字符串强制转换为空字符串 ""。如果您有很多城市和对它们的大量查询,您可以在合并字段上创建索引以促进搜索。

"SELECT location.id FROM location WHERE COALESCE(location.city, '') = :city "

关于sql - PostgreSql 删除 null 和空字符串之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46560802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com