pointholds 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?
Calculate the distances between each two points first, and then display the minimum one.\n
To get the distances of each two points, we need to join this table with itself and use
ABS() function since the distance is nonnegative.\nOne trick here is to add the condition in the join to avoid calculating the distance between a point with itself.
SELECT\n p1.x, p2.x, ABS(p1.x - p2.x) AS distance\nFROM\n point p1\n JOIN\n point p2 ON p1.x != p2.x\n;\n
Note: The columns p1.x, p2.x are only for demonstrating purpose, so they are not actually needed in the end.\n
Taking the sample data for example, the output would be as below.\n
| x | x | distance |\n|----|----|----------|\n| 0 | -1 | 1 |\n| 2 | -1 | 3 |\n| -1 | 0 | 1 |\n| 2 | 0 | 2 |\n| -1 | 2 | 3 |\n| 0 | 2 | 2 |\n
At last, use
MIN() to select the smallest value in the distance column.
SELECT\n MIN(ABS(p1.x - p2.x)) AS shortest\nFROM\n point p1\n JOIN\n point p2 ON p1.x != p2.x\n;\n