我'有两个表会议和在线
会话
| id | time |
| 1 | 1413170771 |
| 2 | 1413174398 |
| 7 | 1413174567 |
在线
| id | username | city | lat | lon |
| 1 | Jon | Toronto | 45.4642700 | 9.1895100 |
| 2 | Danny | Ottawa | 46.5645600 | 9.3456883 |
| 7 | Martin | Calgary | 46.6775339 | 9.5469944 |
我需要从会话和所有在线用户中抽出所有时间并订购它。
例如,如果Martin希望看到所有在线用户并与他保持距离,则结果必须
| id | Users | distance | time |
| 7 | Martin | 0 | 1413174567 |
| 1 | Jon | 100 | 1413170771 |
| 2 | Danny | 250 | 1413174398 |
问题是:
我需要从在线表中提取Martin lat和lon然后计算距离,我想要的距离使用此查询
$R = 3959;
$lat= ???
$lon= ????
SELECT *, (
$R * acos( cos( radians($lat) ) * cos( radians( lat ) )
* cos( radians( lon ) - radians($lon) ) + sin( radians($lat) ) * sin(radians(lat)) ) ) AS distance
FROM online
HAVING distance < $rad
ORDER BY distance
LIMIT 0 , 20"
答案 0 :(得分:1)
一个程序可以发挥魔力,检查出来
-- Trigger DDL Statements
DELIMITER //
DROP PROCEDURE IF EXISTS cal_distance;
CREATE PROCEDURE cal_distance (IN var_id INT)
BEGIN
DECLARE R INT DEFAULT 0;
DECLARE var_lat DOUBLE DEFAULT 0; -- NOT USED?
DECLARE var_lon DOUBLE DEFAULT 0; -- NOT USED?
--GET lon and lat for John
SELECT lat INTO var_lat, lon INTO var_lon
FROM online
WHERE id = var_id;
SELECT *, (
R * acos(cos(radians(var_lat)) * cos(radians(var_lat))
* cos(radians(lon) - radians(var_lon)) + sin(radians(var_lat)) * sin(radians(lat))) ) AS distance
FROM online LEFT JOIN session
USING (id)
HAVING distance >= 0
ORDER BY distance
END $$
DELIMITER ;
调用程序
CALL cal_distance (1);
如果您想避免产程,请尝试
SET @R = 3959;
SET @var_lon = NULL;
SET @var_lat = NULL;
SELECT lat, lon INTO @var_lat, @var_lon
FROM online
WHERE id = 1;
SELECT *, (
@R * acos( cos( radians(@var_lat) ) * cos( radians( lat ) )
* cos( radians( lon ) - radians(@var_lon) ) + sin( radians(@var_lat) ) * sin(radians(lat)) ) ) AS distance
FROM online LEFT JOIN session
USING (id)
HAVING distance >= 0
ORDER BY distance
<强> DEMO 强>
只是使用子查询,但我不喜欢这种方式。
SELECT *, (
3959* acos( cos( radians(var_lat) ) * cos( radians( lat ) )
* cos( radians( lon ) - radians(var_lon) ) +
sin( radians(var_lat) ) * sin(radians(lat)) ) ) AS distance
FROM online, (SELECT lat AS var_lat, lon AS var_lon FROM online WHERE id = 1) AS new_table
HAVING distance >= 0
ORDER BY distance
<强> DEMO 强>