SQL:在二维正方形和圆形中搜索最近的

发布于 2024-09-25 01:23:22 字数 398 浏览 0 评论 0原文

我有一个表:点

它有 2 个字段:X,Y

每行代表 2d 字段上的一个点

我希望能够在某个半径 R 中执行点搜索,例如

alt text

与 A 边呈正方形,如

alt text

顺便说一句:我使用 PHP 访问我的数据库。

我的要点是最接近图形点的中心作为 quqe 中的第一个结果 alt text

如何在 SQL 中执行此类操作?

I have a table: points

it has 2 filds: X, Y

each row represents a dot on 2d field

I want to be capable of performing search of dots with in some radius R like

alt text

and is square with side A like

alt text

BTW: I use PHP to access my DB.

My main point is to get nearest to center of figure point as first result in the quqe like
alt text

How to do such thing in SQL?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱的十字路口 2024-10-02 01:23:22

数学上圆中的点满足方程

(c.X-p.X)^2 + (c.Y-p.Y)^2 <= R^2

其中 c 是圆的中心点,p - 点,R - 半径

对于正方形

max(abs(c.X-p.X),abs(c.Y-p.Y)) <= A/2

其中 c< /strong> 是正方形的中心,p - 点,A - 正方形的边

您可以用任何语言编写这些方程。

方程左侧称为各种测量距离。为了找到最近的点,您应该按距离升序对结果集进行排序,并获取第一个结果。

像这样的东西:

select top 1 p.X, p.X from Points p
otrder by ((@x - p.X)*(@x - p.X)+(@y - p.Y)*(@y - p.Y))

Mathematically point in circle statisfies equation

(c.X-p.X)^2 + (c.Y-p.Y)^2 <= R^2

Where c is the cetner of circle, p - point, R - radius

For square

max(abs(c.X-p.X),abs(c.Y-p.Y)) <= A/2

Where c is the cetner of square, p - point, A - side of square

You can just write theese equations in any language.

Left side of equations called distance for various measures. For finding nearest point you should order resultset by distance asceniding and take first result.

Something like this:

select top 1 p.X, p.X from Points p
otrder by ((@x - p.X)*(@x - p.X)+(@y - p.Y)*(@y - p.Y))
憧憬巴黎街头的黎明 2024-10-02 01:23:22

如果您的查询不是应用程序的核心,Gandjustas 的答案是一个不错的解决方案。如果此几何/空间数据对您非常重要,并且您在处理此类数据时需要速度,那么您应该考虑 RDBMS 的地理空间扩展。

我假设你使用mysql,你有空间扩展 任你处置。
使用正确的数据类型和索引,将为您提供

距离(g1, g2)

和其他有用的函数。

Gandjustas answer is an ok solution if the your queries are not the core of your application. If this geometircal/spatial data is very important to you and you need speed when working with such data specifically you should look into geospatial extensions for your RDBMS.

I will assume that you use mysql, you have spatial extensions on your disposal.
With proper data types and indexes that will give you

Distance(g1, g2)

and other usefull functions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文