我刚开始将 MySQL 与 PHP 结合使用,我想知道是否可以创建自定义函数。此代码片段应说明我正在尝试做什么。
// a somewhat complicated formula not suitable to embed into the query
function Distance($latA, $lonA, $latB, $lonB)
{
// earth's radius
$radius = 3956;
$latA = deg2rad($latA);
$lonA = deg2rad($lonA);
$latB = deg2rad($latB);
$lonB = deg2rad($lonB);
// calculate deltas
$deltaLat = $latB - $latA;
$deltaLon = $lonB - $lonA;
// calculate Great Circle distance
$result = pow(sin($deltaLatitude / 2.0), 2) + (cos($latA) * cos($latB) * pow(sin($deltaLon / 2.0), 2));
$distance = $radius * 2 * atan2(sqrt($result), sqrt(1 - $result));
return $distance;
}
// how can I call Distance() in my query?
$query = "SELECT lat, lon FROM zipcodes WHERE Distance(lat, lon, 0, 0) < 20";
mysql_query($query);
在此先感谢您的帮助!
最佳答案
您可以在您的应用程序中声明此 MySQL 函数,它将保留在数据库中,直到数据库服务器重新启动。
mysql_query("CREATE FUNCTION Distance(LAT_A INT, LON_A INT, LAT_B INT, LON_B INT, )
RETURNS INT
READS SQL DATA
DETERMINISTIC
BEGIN
DECLARE radius, deltaLat, deltaLon, result, distance BIGINT;
SET radius=3956;
SET deltaLat=LAT_B-LAT_A;
SET deltaLon=LON_B-LON_A;
SET result=POW(SIN(deltaLat/2), 2) + (COS(LAT_A) * COS(LAT_B) * POW(SIN(deltaLon/2.0), 2));
SET distance=radius * 2 * ATAN2(SQRT(result), SQRT(1 - result));
RETURN distance;
END");
这使用了 MySQL 的 mathematical functions .将此处理卸载到数据库既快速又高效(数据不必通过网络传输,您只会返回所需的结果)。
一旦你声明了它,你就可以像这样使用它:
$query = "SELECT lat, lon FROM zipcodes WHERE Distance(lat, lon, 0, 0) < 20";
mysql_query($query);
但是,如果您的数据库确实重新启动,则之前声明的任何函数或过程都将丢失。可以在应用程序级别优雅地处理 MySQL 错误 1305(Function functionName does not exist
)。
在您的数据库错误处理程序中:
switch (mysql_errno()):
case 1305:
if (false === $database->_declareStoredProcedureFlag) {
if ($c = preg_match_all("/FUNCTION [a-zA-Z0-9]+\." .
"([a-zA-Z0-9_]*) does not exist/is",
mysql_error(), $matches)
) {
$storedFunctionName = $matches[1][0];
$database->_declareStoredProcedureFlag = true;
if (true === $database->declareStoredFunction($storedFunctionName)) {
$result = mysql_query($query);
}
}
}
break;
...
关于php - 创建自定义 MySQL 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7208730/