简体   繁体   中英

Mysql query very slow (group by)

mysql query very slow but i use "group by" function...

i remove group by query and query very fast.

How can I solve this problem?

my query code:

$myquery1 = mysql_query("SELECT * FROM konucuklar 
                         WHERE status='' 
                           and category='football' 
                         GROUP BY matchhour 
                         ORDER BY id asc");
while($myquery1record = mysql_fetch_array($myquery1)){

    $myquery2 = mysql_query("SELECT * FROM konucuklar 
                             WHERE mactarihi='$bugunt' 
                               and statu='' 
                               and kategori='futbol' 
                               and macsaati='$myquery1record[matchhour]' 
                             ORDER BY id asc");

     $toplams=@mysql_num_rows($myquery2);


     while ($myquery2record=mysql_fetch_array($myquery2)) {     
// code
     } 
}
}
  1. Your first query does not comply with SQL standards and will be processed by mysql only if strict sql mode is not enabled.
  2. You are issuing the 2nd query in a loop based on the results returned by the 1st query. So, if the 1st query returns 10 rows, then you will execute the 2nd query 10 times. This is very slow. You should rewrite the 2 queries as one, since both queries query the same table and have almost the same where criteria.
  3. No idea what the 2nd while loop does, as I can't see where $listele is defined.

The slow down might not be related to the GROUP BY clause. Try adding an index on columns you need to .

Link to understand index : http://www.tutorialspoint.com/sql/sql-indexes.htm

MySQL Profiling might also help you in your endeavour

Your queries are not optimized and probably could be done better in other way incluiding using only one composed query (JOIN) to fetch all data at once.

Also if your tables have lots of items is good practice to create INDEXES to the fields uses in the common queries for the filter to make the search faster.

Example, your firs select has this complexity (and probably is not well formed)

SELECT * FROM konucuklar WHERE status='' 
                           and category='football' 
                         GROUP BY matchhour 
                         ORDER BY id asc

But is used only to get the matchhour for the second query. The minimal optimization is to use a query to fetch only the required field.

SELECT DISTINCT matchhour FROM konucuklar WHERE status='' and category='football' 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM