这是我的SQLFiddle,这是我的程序
我想将此过程重写为简单操作。
它应该将输入作为Lat,Lng并且相对于给定的Lat和Long返回最近的driverid,lat,long(由desc排序并取第一个记录)。它包含一些我不需要的表格。
(问题是我无法找到哪个字段是必需的,哪个不是?)
DELIMITER //
CREATE PROCEDURE `driver_latlong`(IN `lat` DECIMAL(20,9), IN `lng` DECIMAL(20,9))
BEGIN
SET @sql = CONCAT('SELECT sd.DriverId, sd.Lat, sd.Long, sd1.RadiusOfService, @dist:= ( 6371 * acos( cos( radians(',lat,') ) * cos( radians( sd.Lat ) ) * cos( radians( sd.Long ) - radians(',lng,') ) + sin( radians(',lat,') ) * sin( radians( sd.Lat ) ) ) ) AS distance
, Case When @dist <= 1 Then sd1.DeliveryFeeOne When @dist<= 2 Then sd1.DeliveryFeeTwo When @dist<= 3 Then sd1.DeliveryFeeThree Else sd1.DeliveryFeeMore End as deliveryfee
, Case When @dist <= 1 Then sd1.DeliveryTimeOne When @dist<= 2 Then sd1.DeliveryTimeTwo When @dist<= 3 Then sd1.DeliveryTimeThree Else sd1.DeliveryTimeMore End as deliverytime
, sd.ShopName, sd.Address, sd.LogoFile FROM driver_latlong sd LEFT JOIN WHERE sd.Status = \'1\' and sd.Lat != 0 and sd.Long != 0 AND ( 6371 * acos( cos( radians(',lat,') ) * cos( radians( sd.Lat ) ) * cos( radians( sd.Long ) - radians(',lng,') ) + sin( radians(',lat,') ) * sin( radians( sd.Lat ) ) ) ) <= sd1.RadiusOfService ORDER BY distance ASC;');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
注意:实际上我从之前的项目中得到了这个程序,所以不需要其他表只我们引用的表是driver_latlong
由于
答案 0 :(得分:0)
我假设你不太关心地球的曲率,所以我将long和lat视为方形网格上的轴。它使用Pythagoras使计算变得相当简单。
DELIMITER //
CREATE PROCEDURE `getNearestDriver` (
IN `inLat` DECIMAL(20,9), IN `inLong` DECIMAL(20,9),
OUT `outDriverId` INT(11), OUT `outLat` FLOAT, OUT `outLong` FLOAT
)
BEGIN
SELECT
`DriverId`, `Lat`, `Long` INTO `outDriverId`, `outLat`, `outLong`
FROM `driver_latlong`
# If the difference in lat and long make up two sides of a
# right angled triangle then the hypotenuse is the distance.
ORDER BY ( POWER(`inLat` - `Lat`, 2) + POWER(`inLong` - `Long`, 2) )
LIMIT 1;
END//
DELIMITER ;
SET @myLat = 11;
SET @myLong = 77;
SET @DriverId = 0;
SET @DriverLat = 0;
SET @DriverLong = 0;
CALL getNearestDriver( @myLat, @myLong, @DriverId, @DriverLat, @DriverLong );
SELECT @DriverId, @DriverLat, @DriverLong;
DROP PROCEDURE `getNearestDriver`;
DROP TABLE `driver_latlong`;