Table point
holds the x coordinate of some points on x-axis in a plane, which are all integers.
Write a query to find the shortest distance between two points in these points.
| x |
|-----|
| -1 |
| 0 |
| 2 |
The shortest distance is '1' obviously, which is from point '-1' to '0'. So the output is as below:
| shortest|
|---------|
| 1 |
Note: Every point is unique, which means there is no duplicates in table point
.
Follow-up: What if all these points have an id and are arranged from the left most to the right most of x axis?
題目描述:求兩點間的最短距離。
題目分析:利用 sql
語句查詢兩點間最短距離,將 x1
表和 x2
表連接起來,去除兩個表的重複項即可。
MySQL
語句如下:
SELECT
MIN(ABS(x1.x - x2.x)) AS shortest
FROM
point AS x1
JOIN
point AS x2
WHERE
x1.x != x2.x