1

有谁知道是否可以在一个查询中执行以下操作而不是执行 numrows?

$select1 = "SELECT service FROM UPSServices WHERE code = '$serviceCode' AND ship_from_code = '$shipFrom'";

$result = mssql_query($select1);

//print_r($result);

if(mssql_num_rows($result) == 0) {
    $select2 = "SELECT service FROM UPSServices WHERE code = '$serviceCode' AND ship_from_code IS NULL";
    $result = mssql_query($select2);
}

while ($service = mssql_fetch_array($result)) {
    return $service['0'];
}
4

2 回答 2

1

您正在使用 SQL Server,因此您可以执行此操作。它比您预期的要复杂一些。以下版本计算有效值的数量。如果这大于 0,则过滤掉 NULL。

select service    
from (SELECT service,
             count(ship_from_code) over () as NumValues
      FROM UPSServices
      WHERE code = '$serviceCode' AND (ship_from_code = '$shipFrom' OR ship_from_code IS NULL) 
    ) t
where (NumValues > 0 and service is not NULL) or (NumValues = 0 and service is NULL)
limit 1
于 2012-12-12T15:14:36.340 回答
0

如果指定的 shipCode 不存在,我认为您需要 NULL shipCode 的值

SELECT service FROM UPSServices WHERE 
code = '$serviceCode' AND (ship_from_code = '$shipFrom' OR ship_from_code IS NULL) 
ORDER BY ship_from_code"

Order by 将确保如果您的船代码存在,那么它在顶部

于 2012-12-12T13:51:18.693 回答