我刚开始使用
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) < 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,0) < 20"; MysqL_query($query);
但是,如果数据库重新启动,则先前声明的任何函数或过程都将丢失.可以在应用程序级别正常处理MysqL错误1305(函数functionName不存在).
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; ...