MySQL - SELECT col,function(col)WHERE IN(..)返回相同的值

时间:2015-07-21 18:30:05

标签: mysql stored-procedures haversine

我已经定义了一个使用半正弦公式计算最近项目的函数。当我以ad-hoc方式执行查询时,此函数正常工作,例如:

SELECT CONCAT(address, ", ", deadline, ", NC") AS addr FROM tblTickets WHERE ticket = 'A152012363' LIMIT 1 INTO @Address;
SELECT lat, lng FROM AddressGeocode WHERE address = @Address LIMIT 1 INTO @LAT, @LNG;
SELECT ROUND(( 3959 * acos( cos( radians(@LAT) ) * cos( radians( startlat ) ) * cos( radians( startlon ) - radians(@LNG) ) + sin( radians(@LAT) ) * sin( radians( startlat ) ) ) ) * 5280.0 ) AS distance
FROM tblAsBuiltPolys
ORDER BY distance
LIMIT 1 INTO @RET;
SELECT @RET

当我将逻辑放在一个函数中以便我可以重新使用它时,结果总是一样的,直到我开始另一个会话。

我最初认为问题在于我正在使用会话变量,因此我将功能调整为:

CREATE FUNCTION `getTicketBuffer`(`ticket` VARCHAR(50))
    RETURNS DOUBLE
    LANGUAGE SQL
    NOT DETERMINISTIC
    READS SQL DATA
    COMMENT ''
BEGIN
DECLARE ADDR VARCHAR(250) DEFAULT NULL;
DECLARE LT DOUBLE DEFAULT NULL;
DECLARE LG DOUBLE DEFAULT NULL;
DECLARE RET DOUBLE DEFAULT NULL;

SET ADDR = (SELECT CONCAT(address, ", ", deadline, ", NC") AS addr FROM tblTickets WHERE ticket = ticket LIMIT 1);
SELECT lat, lng INTO LT, LG FROM AddressGeocode WHERE address = ADDRESS LIMIT 1;
SET RET = (SELECT ROUND(( 3959 * acos( cos( radians(LT) ) * cos( radians( startlat ) ) * cos( radians( startlon ) - radians(LG) ) + sin( radians(LT) ) * sin( radians( startlat ) )     ) ) * 5280.0 ) AS distance
    FROM tblAsBuiltPolys
    ORDER BY distance
    LIMIT 1);
RETURN RET;
END

我正在努力使我的头发工作,以便以下查询将正确执行。

SELECT ticket, getTicketBuffer(ticket) AS d 
FROM tblTickets WHERE ticket IN
("A152012363","C152011366","A152012358","C152011309","A152012353","A152011315");

当我直接在查询中执行逻辑时,我得到以下内容:

mysql> SELECT ROUND(( 3959 * acos( cos( radians(@LAT) ) * cos( radians( startlat ) ) * cos( radians( startlon ) - radians(@LNG) ) + sin( radians(@LAT) ) * sin( radians( startlat ) ) ) ) * 5280.0 ) AS distance
-> FROM tblAsBuiltPolys
-> ORDER BY distance
-> LIMIT 1 INTO @RET;
Query OK, 1 row affected (0.02 sec)

mysql> SELECT @RET
    -> ;
+------+
| @RET |
+------+
|  130 |
+------+
1 row in set (0.00 sec)

mysql>
mysql> SELECT ticket, getTicketBuffer(ticket) AS d FROM tblTickets WHERE ticket IN("A152012363","C152011366","A152012358","C152011309","A152012353","A152011315");
+------------+------+
| ticket     | d    |
+------------+------+
| A152011315 |   81 |
| A152012353 |   81 |
| A152012358 |   81 |
| A152012363 |   81 |
| C152011309 |   81 |
| C152011366 |   81 |
+------------+------+
6 rows in set (0.12 sec)

我试图在门票列表中为每张门票获取“TicketBuffer”,如果可以将其设置为视图,那么这也可以。

有没有人看到任何明显的错误?我不是SQL的专家,特别是存储的函数/程序,所以我相信这可以做得更好。

0 个答案:

没有答案