过滤依赖数据 table,returns 结果来自主要 table

Filtering dependent data table, returns results from main table

我可以在 dependent 数据中搜索 tables 但 returns 结果来自 main table?

当我们在数据库中有 N x N 关系时会出现此问题,如下例所示:每个用户都可以有多个位置,但即使用户有多个位置,它仍然是一个自然人。

我想在 table locations 和 return 条件下查询 sphinx set should be from table users .

Query results will be filter by geo coordinates GEODIST() but its only information because its not the main subject of this question. Goal is for example: find persons who have location in 20 kilometers radius from some explicit point.

SQL结构

TABLE users
id PRIMARY KEY
name TEXT
etc...

TABLE locations
id PRIMARY KEY
name TEXT
coord_x FLOAT
coord_y FLOAT
etc...

TABLE user_location
user_id INTEGER FK
location_id INTEGER FK

当然,我可以简单地在 Sphinx sql_query 中加入这 3 table 并过滤这个集合,但是当人有更多时我得到了 重复的人 不止一处。

关于如何使用 Sphinx 搜索实现此目标的任何提示?

SELECT DISTINCT u.*
FROM users u
JOIN user_location ul ON ul.user_id = u.id
JOIN locations l ON l.id = ul.location_id
WHERE ((l.coord_x - <<your X>>) * (l.coord_x - <<your X>>)) +
      ((l.coord_y - <<your Y>>) * (l.coord_y - <<your Y>>)) < 400;

您可能希望将其包装在一个 SQL 语言函数中,该函数将位置坐标作为参数,也可能将距离作为参数。请注意,此代码假定 coord_x 和 coord_y 以千米为单位。如果在其他单元中,相应地更改值 400。

另请注意,该查询不会通过计算两个基本方向上的平方差的平方根来计算到给定点的距离:您对距离本身不感兴趣,而只对比 a 更近的位置感兴趣距指定点的指定距离。因此,您对该距离求平方,然后忘记计算量很大的平方根。如果您的位置 table 有很多记录,您会注意到其中的差异。

Of course I can simply JOIN this 3 tables in Sphinx sql_query and filter this set but then I got duplicated persons when person have more than one location.

只需将 GROUP BY 添加到 sphinx 查询,然后每个用户将只获得自己的行。


您需要将 users.id 设为 sphinx 属性 (因此可以对其进行分组)并使用来自 user_location 的主键作为 sphinx文档 ID(因此它是唯一的)

(如果有 没有 位置的用户,并且仍然希望能够在没有位置过滤器的情况下进行搜索,则会变得更加复杂。但是它仍然可以完成。也许在索引上使用第二个来源,以找到未定位的用户)

SELECT *
FROM users u
WHERE EXISTS (
  SELECT * FROM user_location ul
  JOIN locations l ON l.id = ul.location_id
  WHERE ul.user_id = u.id
  AND l.coord_x ...
  AND l.coord_y ...
  );