doujin8673 2013-10-18 06:46
浏览 88
已采纳

按查询排序需要花费太多时间

I have 80k plus customers and having 4 groups. Now I want to find 2 groups users with a query in mysql. My query is like below:

select c.customers_firstname as recipient_firstname, 
       c.customers_lastname as  recipient_lastname,
       c.customers_id as recipient_id, 
       c.customers_email_address as recipient_email_address 
from customers c
where customers_group_id = '1' OR customers_group_id = '3'

When I run this query in phpmyadmin I got the result : Showing rows 0 - 29 ( 59,815 total, Query took 0.0034 sec)

But when I added order by ORDER BY recipient_firstname ASC in this query the result time is : Showing rows 0 - 29 ( 59,815 total, Query took 0.2607 sec)

the order by query is taking too much time for the result.

I want to reduce the time of order by query.

Please help if there is another way to get the same result in less time.

  • 写回答

4条回答 默认 最新

  • dougao1542 2013-10-18 06:51
    关注

    You need an index on the recipient_firstname field (so really customers.customers_firstname). An index allows for an ordered, linear time iteration over the result set.

    If you don't have an index, the result set must be aggregated and then sorted. This sorting is going to be n log n. That's obviously pretty slow for large sets, and if it can't fit into memory (and 60k records might not depending on configuration), it's going to do a very slow file based sort.

    tl;dr You need an index. An index on recipient_firstname will make the query extremely close in performance to the non ORDER BY version.


    By the way, if customers_group_id is an integral field, use integer literals, not strings. It likely won't make a difference, but it's misleading, and there are actually a few situations where it matters.


    Depending on the situation, it's probably also worth putting an index on the group id. For small sets, the results can just be filtered as the set is built, but for large result sets, that will end up requiring a rather disk heavy full table scan.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)