MySQL group-by very slow

后端 未结 5 2142
予麋鹿
予麋鹿 2021-02-07 05:34

I have the folowwing SQL query

SELECT CustomerID FROM sales WHERE `Date` <= \'2012-01-01\' GROUP BY CustomerID

The query is executed over 11

相关标签:
5条回答
  • 2021-02-07 05:53

    I had the same problem, I changed the key fields to the same Collation and that fix the problem. Fields to join the tables had different Collate value.

    0 讨论(0)
  • 2021-02-07 06:07

    Without knowing what your table schema looks like, it's difficult to be certain, but it would probably help if you added a multiple-column index on Date and CustomerID. That'd save MySQL the hassle of doing a full table scan for the GROUP BY statement. So try ALTER TABLE sales ADD INDEX (Date,CustomerID).

    0 讨论(0)
  • 2021-02-07 06:11

    Try putting an index on (Date,CustomerID).

    Have a look at the mysql manual for optimizing group by queries:- Group by optimization

    You can find out how mysql is generating the result if you use EXPLAIN as follows:-

    EXPLAIN SELECT CustomerID FROM sales WHERE `Date` <= '2012-01-01' GROUP BY CustomerID
    

    This will tell you which indexes (if any) mysql is using to optimize the query. This is very handy when learning which indexes work for which queries as you can try creating an index and see if mysql uses it. So even if you don't fully understand how mysql calculates aggregate queries you can create a useful index by trial and error.

    0 讨论(0)
  • 2021-02-07 06:11

    try this one :

    SELECT distinct CustomerID FROM sales WHERE `Date` <= '2012-01-01'
    
    0 讨论(0)
  • 2021-02-07 06:16

    Wouldn't this one be a lot faster and achieve the same?

    SELECT DISTINCT CustomerID FROM sales WHERE `Date` <= '2012-01-01'
    

    Make sure to place an index on Date, of course. I'm not entirely sure but indexing CustomerID might also help.

    0 讨论(0)
提交回复
热议问题