表 point_2d 保存了所有点(多于 2 个点)的坐标 (x,y) ,这些点在平面上两两不重合。
写一个查询语句找到两点之间的最近距离,保留 2 位小数。
x | y |
---|---|
-1 | -1 |
0 | 0 |
-1 | -2 |
最近距离在点 (-1,-1) 和(-1,2) 之间,距离为 1.00 。所以输出应该为:
shortest |
---|
1.00 |
--建表语句
CREATE TABLE If Not Exists point_2d (x INT NOT NULL, y INT NOT NULL)
Truncate table point_2d
insert into point_2d (x, y) values ('-1', '-1')
insert into point_2d (x, y) values ('0', '0')
insert into point_2d (x, y) values ('-1', '-2')
--答案1
--自连接后过滤,点与点之间欧几里得距离,需要使用sqrt函数与pow函数
select
min(round(sqrt(pow(p1.x-p2.x,2)+pow(p1.y-p2.y,2)),2)) as shortest
from
point_2d p1 join
point_2d p2 on
p1.x<>p2.x or p1.y<>p2.y