我'有两个表会话和在线
| 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 |
查询
SELECT * , ( 6371 * acos( cos( radians( 45.4642700 ) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians( 9.1895100 ) ) + sin( radians( 45.4642700 ) ) * sin( radians( lat ) ) ) ) AS distance
FROM online AS o
INNER JOIN sessions AS s ON o.id = s.id
HAVING distance <2000
ORDER BY username DESC
如何优化此查询?我有会话ID的索引和在线ID我可以为临时表添加索引吗?
答案 0 :(得分:0)
假设您有以下表格
| id | time |
| 1 | 1413170771 |
| 2 | 1413174398 |
| 7 | 1413174567 |
在线改为
| id | username | city | lat | lon | dist |
| 1 | Jon | Toronto | 45.4642700 | 9.1895100 | ........ |
| 2 | Danny | Ottawa | 46.5645600 | 9.3456883 | ........ |
| 7 | Martin | Calgary | 46.6775339 | 9.5469944 | ........ |
以下查询:
SELECT *
FROM session s, online o
WHERE s.dist < 2000
AND s.id = o.id
ORDER BY username DESC;