MySQL超时问题

时间:2015-10-15 14:53:17

标签: php mysql timeout

我在Linux服务器上与PHP和MySql相关的训练中遇到严重问题,而当我在localhost中运行相同的数据库相同的代码时,它工作正常。

我在数据库表中有近30,000条记录,而mysql是:

SELECT * FROM tbl_movies where id not in (select movie_id from tbl_usermovieque where user_id='3' union 
                                      select movie_id from tbl_user_movie_response where user_id='3' union 
                                      select movie_id from tbl_user_movie_fav where user_id='3') and id < 220 order by rand() limit 0,20

我的本​​地主机和我们的linux服务器上的INFINITE需要0.0010秒。我找不到原因。

由于 哈拉

1 个答案:

答案 0 :(得分:1)

您能否确认此返回相同的结果?它应该更快这种方式。联盟在某个时候是有用的,但没有真正优化。

SELECT * FROM tbl_movies where id not in (
    select distinct movie_id
    from tbl_movies m
    inner join tbl_usermovieque um ON um.movie_id = m.movie_id = m.movie_id
    inner join tbl_user_movie_response umr ON umr.movie_id = m.movie_id = m.movie_id
    inner join tbl_user_movie_fav umf ON umf.movie_id = m.movie_id = m.movie_id
    where um.user_id = 3 or umr.user_id = 3 or umf.user_id = 3
) and id < 220 order by rand() limit 0,20;

PS:我假设你有索引un oser_id和id_movie

编辑:您的问题可能来自rand()

MySQL order by optimization在页面中查找RAND():在评论中有一些性能测试=&gt; rand()单独接缝是一个糟糕的解决方案

  

性能

     

现在让我们看看我们的表现会发生什么。我们有3个不同   寻求解决我们的问题。

     
      
  • Q1。 ORDER BY RAND()
  •   
  • Q2。兰德()* MAX(ID)
  •   
  • Q3。 RAND()* MAX(ID)+ ORDER BY ID
  •   
     

预计Q1将花费N * log2(N),Q2和Q3几乎不变。

     

获取实数值我们用N行填充表(一千到一行)   一百万)并执行每次查询1000次。

     

行|| 100 || 1.000 || 10.000 || 100.000 || 1.000.000

     

Q1 || 0:00.718s || 0:02.092s || 0:18.684s || 2:59.081s || 58:20.000s   Q2 || 0:00.519s || 0:00.607s || 0:00.614s || 0:00.628s || 0:00.637s   Q3 || 0:00.570s || 0:00.607s || 0:00.614s | 0:00.628s || 0:00.637s

     

正如你所看到的那样,简单的ORDER BY RAND()已经落后了   表中只有100行的优化查询。