MySQL ORDER BY最近的区域


MySQL ORDER BY nearest zone

基本上,我必须使用算法来显示所选区域和其他区域中的餐厅,这实际上是有意义的。。

例如:如果我所在的地区在某个城市的北部,我想去北部的餐馆,然后搬到中部,然后搬到东部,然后搬到西部,最后搬到相反的地方,即南部

在东部的情况下,然后是中部、北部、南部,最后是极端相反的情况,即西部

我的数据库中有以下

带ID的分区表,1-北部,2-东部,3-西部,4-南部,5-中部。

每个城市和结构的位置/面积表称为

locality_id | locality_name | zone_id(FK)

我有我的模型(php/codeigniter)

$this->db->select('menu_item.restaurant_id, menu_item.price, localities.locality_name, restaurant_information.restaurant_name, restaurant_information.restaurant_address, restaurant_information.is_halal, restaurant_information.cuisine, restaurant_information.city, restaurant_information.pincode');
$this->db->from('menu_item');
$this->db->where('menu_item.dish_id', $dish_id);
$this->db->where('menu_item.is_active', 1);
$this->db->where('restaurant_information.is_active', 1);
$this->db->join('restaurant_information', 'menu_item.restaurant_id = restaurant_information.restaurant_id');
$this->db->join('localities', 'restaurant_information.locality_id = localities.locality_id');

如果我有太多的联接或其他什么都没关系。。但绝对不是用lat/long或谷歌地理。。

请帮帮我。。我尝试了order_by_field。。它还可以,而且有效,但我不能动态地给出它。。

有什么解决方案吗?还是我朝着错误的方向走了。。?如果我把结构弄错了,请纠正我。。!

我也准备好了,如果可以在结果对象上按部分进行排序,我可以在那里获取结果并根据位置进行排序。。但我更喜欢MySQL来做这项工作。提前感谢

基本上,如果我理解得很好,你想按最近的区域排序。

所以也许你应该把你的id 1,2,3,4,5翻译成坐标,比如:

  • 1北:x:0,y:1
  • 2东部:x:1,y:0
  • 3西部:x:-1,y:0
  • 4南:x:0,y:-1
  • 5中心:x:0,y:0

然后根据计算出的距离对它们进行排序。


示例:您位于西部,在的西部、北部、南部和中部都有餐厅

如果你有坐标,你可以计算距离,然后对结果进行排序:

  • 西餐厅距离0
  • 北餐厅距离1.2xxx(差不多)
  • 南餐厅距离1.2xxx(差不多)
  • 中央餐厅距离1

因此,假设您已经实现了函数GET_DISTANCE()&GET_COORD()你会有

SELECT
  menu_item.restaurant_id
, menu_item.price
, localities.locality_name
, restaurant_information.restaurant_name
, restaurant_information.restaurant_address
, restaurant_information.is_halal
, restaurant_information.cuisine
, restaurant_information.city
, restaurant_information.pincode
FROM menu_item
JOIN restaurant_information
  ON (menu_item.restaurant_id = restaurant_information.restaurant_id)
JOIN localities
  ON (restaurant_information.locality_id = localities.locality_id)
WHERE TRUE
  AND menu_item.dish_id = $dish_id
  AND menu_item.is_active = 1
  AND restaurant_information.is_active = 1
ORDER BY
  GET_DISTANCE(
    GET_COORD($my_position)
  , GET_COORD(restaurant_information.locality_id)
  )
;