我有 3 张 table 。
表 1 - 驱动程序
表 2 - 位置
表 3 - 距离
用户将搜索与位置匹配的驱动程序。在驱动程序表中,位置是指驱动程序的当前位置。如果驱动程序在特定位置不可用,我希望通过查询来搜索最接近用户提供的位置的驱动程序。
表2是地点名称,表3是从一个地方到另一个地方的距离。但问题是,如果存储了从locationid 1到locationid 2的距离,则相反的版本则不存储(locationid 2到locationid 1)。
最佳答案
这并不简单。
首先,您需要获取与给定位置有关系的所有位置。此结果包括 locationid
和distance
.
与位置本身的距离为零。我已经得到了UNION ALL
的帮助为了列出 <locationid,distance>
.
然后创建一个INNER JOIN
在上面的列表和您的 drivers
之间匹配表location
.
最后根据distance
对结果集进行排序按升序排列。
SELECT
*
FROM drivers DR
INNER JOIN
(
SELECT
locationid,
0 AS distance
FROM location
WHERE locationname = 'Gulshan'
UNION ALL
SELECT
IF(L.locationid = D.fromid, D.toid, D.fromid),
D.distance
FROM location L
INNER JOIN distance D ON L.locationid IN (D.fromid,D.toid)
WHERE locationname = 'Gulshan'
) AS t
ON DR.location = t.locationid
ORDER BY t.distance
或者
注意:您可以包括 LIMIT n
为了限制结果集最多包含 top n
搜索结果。
您还可以添加 ..WHERE distance < MAX_ALLOWABLE_DISTANCE...
在您的查询中,以便最终结果具有某种意义。
关于mysql - 从给定位置的最近位置查找司机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40067616/