MySQL ORDER BY最近的区域

时间:2013-11-27 12:37:51

标签: php mysql sql codeigniter sorting

基本上我必须让算法在所选区域和其他区域中显示实际有意义的餐馆。

例如:如果我的地区位于某个城市的北部,我想在北方出现餐馆,然后移到中央,然后到东部再到西部,最后到达对面即南部。

在东部,然后是中部,北部,南部,最后是极端对面,即西部

我在我的数据库中有以下

带有ids的区域表,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或google geo ..

请帮帮我..我尝试了order_by_field ..没关系,但是它有效,但我无法动态给它..

有没有解决方案,或者我朝错误的方向走了......?如果我的结构错了,请纠正我..!

我也准备好了,如果可以在结果对象上完成订单,我可以获取结果并根据位置对其进行排序..但我更喜欢MySQL来完成这项工作。提前致谢

1 个答案:

答案 0 :(得分:0)

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

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

  • 1 North:x:0,y:1
  • 2 East:x:1,y:0
  • 3 West:x:-1,y:0
  • 4南:x:0,y:-1
  • 5中心:x:0,y:0

然后按距离计算它们。


示例:您位于West,您的餐厅位于West,North,South和Central

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

  • 西餐厅距离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)
  )
;
相关问题