我的主要目标是在MySQL中创建一个 PROCEDURE ,以根据传递的纬度和经度查询位置。该查询获取传递给 PROCEDURE 的特定半径内的位置的id,纬度和经度。我还尝试添加 JOIN 来查询" 照片"每个位置的照片表。
查询部分有效。它需要返回没有双打的所有位置,以及字符串中的所有照片。
GROUP_CONCAT(CONVERT(photos.pid, CHAR(8))) AS photo
通过添加此代码块,查询仅返回1个结果,并将所有照片ID连接到一个字段中,即使它与该位置无关。如果我删除了这段代码,它会返回每个位置中的1个,但是对于任何一个位置有一张或多张相关照片的结果,结果会加倍,所以照片字段需要连接,但我没有正确地执行此操作。 / p>
CREATE PROCEDURE `GEODIST`( IN userid int, IN dist int, IN olat float, IN olon float ) DETERMINISTIC READS SQL DATA
BEGIN
DECLARE mylon DOUBLE;
DECLARE mylat DOUBLE;
DECLARE lon1 FLOAT;
DECLARE lon2 FLOAT;
DECLARE lat1 FLOAT;
DECLARE lat2 FLOAT;
SET mylon = olon;
SET mylat = olat;
SET lon1 = mylon - dist / abs( cos( radians( mylat ) ) * 69 );
SET lon2 = mylon + dist / abs( cos( radians( mylat ) ) * 69 );
SET lat1 = mylat - ( dist / 69 );
SET lat2 = mylat + ( dist / 69 );
SELECT GROUP_CONCAT(CONVERT(photos.pid, CHAR(8))) AS photo, destination.id,
destination.latitude, destination.longitude,
3956 * 2 * ASIN(SQRT( POWER(SIN((origin.latitude -destination.latitude) * pi()/180 / 2), 2)
+COS(origin.latitude * pi()/180) * COS(destination.latitude * pi()/180)
*POWER(SIN((origin.longitude -destination.longitude) * pi()/180 / 2), 2) ))
AS distance FROM locations destination CROSS JOIN locations origin LEFT JOIN photos ON photos.lid = destination.id WHERE origin.id = userid
AND destination.longitude BETWEEN lon1 AND lon2 AND destination.latitude BETWEEN lat1 and lat2
HAVING distance < dist ORDER BY distance LIMIT 50;
END
答案 0 :(得分:1)
我想它应该是这样但我无法测试它。
SELECT
GROUP_CONCAT( CONVERT( DISTINCT( photos.pid ), CHAR(8) ) ) ) AS photo,
destination.id,
destination.latitude,
destination.longitude,
3956 * 2 * ASIN(SQRT( POWER(SIN((origin.latitude -destination.latitude) * pi()/180 / 2), 2)
+COS(origin.latitude * pi()/180) * COS(destination.latitude * pi()/180)
*POWER(SIN((origin.longitude -destination.longitude) * pi()/180 / 2), 2) ))
AS distance
FROM
locations destination
CROSS JOIN
locations origin
LEFT JOIN
photos ON photos.lid = destination.id
WHERE
origin.id = userid
AND
destination.longitude BETWEEN lon1 AND lon2
AND destination.latitude BETWEEN lat1 and lat2
HAVING distance < dist
GROUP BY
destination.id
ORDER BY
distance
LIMIT 50;