stored procedures - MySQL - SELECT col, function(col) WHERE IN (..) returns same value -
i have defined function calculates nearest item using haversine formula. function works correctly when execute query in ad-hoc fashion such as:
select concat(address, ", ", deadline, ", nc") addr tbltickets ticket = 'a152012363' limit 1 @address; select lat, lng addressgeocode address = @address limit 1 @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 ) distance tblasbuiltpolys order distance limit 1 @ret; select @ret
when place logic in function can re use it, result same until start session.
i thought issue was using session variables adjusted function this:
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") addr tbltickets ticket = ticket limit 1); select lat, lng lt, lg addressgeocode 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 ) distance tblasbuiltpolys order distance limit 1); return ret; end
i pulling hair out trying make work following query execute correctly.
select ticket, getticketbuffer(ticket) d tbltickets ticket in ("a152012363","c152011366","a152012358","c152011309","a152012353","a152011315");
when exectute logic directly in query following:
mysql> select round(( 3959 * acos( cos( radians(@lat) ) * cos( radians( startlat ) ) * cos( radians( startlon ) - radians(@lng) ) + sin( radians(@lat) ) * sin( radians( startlat ) ) ) ) * 5280.0 ) distance -> tblasbuiltpolys -> order distance -> limit 1 @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) d tbltickets 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)
i trying "ticketbuffer" each ticket in list of tickets, if can made view, work well.
does see obvious mistakes? not expert @ sql, particularly stored functions/procedures sure can done better way.
Comments
Post a Comment