duan00529 2012-07-31 21:33 采纳率: 100%
浏览 35

MySQL与PHP查询性能问题

I have a sql query that runs in like 2 seconds in mysql (Navicat) and it runs through 600,000 locations returning all the table data and calculates the distance between a lat and long that I put in.

The SQL is something like this:

select *, 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - 
radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance 
FROM places 
GROUP BY places.user_id
HAVING distance > 0
ORDER BY distance LIMIT 0 , 10;

In the above query 37 and -122 are passed into the query as lat and long.

When I run this in Navicat, it's 2 seconds, but it takes minutes in Cakephp or straight php using mysql_query().

Why does this occur and how do I fix it?

I'm running both MySQL and Apache locally on a Win7 4GB box running XAMPP.

  • 写回答

1条回答 默认 最新

  • douliaotong4944 2012-08-01 02:24
    关注

    This could be related to your table structure. If you have not already, I would highly recommend you create an index on user_id in the places table. This can make a surprising difference in execution time for complex queries.

    Also, since it seems you are doing a fair amount of calculation in the query ( for distance ), you may benefit greatly from using the prepared statements feature in the mysqli or PDO extensions - instead of using the older, slower, less-safe, deprecated mysql extension.

    This article helps explain the differences: http://php.net/manual/en/mysqli.overview.php

    If you are already accustomed to the mysql extension, I would recommend switching to mysqli - their procedural syntax/API is almost identical ( the main difference is that you will need to provide the $connection_handle as the first argument in many functions, instead of it being the optional final argument ).

    Navicat may be taking advantage of prepared statements, that may be your difference.

    评论

报告相同问题?

悬赏问题

  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。