<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
    <channel>
        <title>MySQL Forums - Optimizer &amp; Parser</title>
        <description>Forum for MySQL Optimizer &amp; Parser.</description>
        <link>http://forums.mysql.com/list.php?115</link>
        <lastBuildDate>Tue, 18 Jun 2013 07:31:45 +0000</lastBuildDate>
        <generator>Phorum 5.2.19</generator>
        <item>
            <guid>http://forums.mysql.com/read.php?115,587032,587032#msg-587032</guid>
            <title>Optimize Inner Join With WHERE BETWEEN dates (7 replies)</title>
            <link>http://forums.mysql.com/read.php?115,587032,587032#msg-587032</link>
            <description><![CDATA[ Is there a way to optimize the query more efficiently? Or do what I'm trying to do a better way? The goal is to find users that have records with overlapping ClockIn-ClockOut ranges. This is a corner stone of a new feature. I suppose the performance is not horrible at around 3 seconds but this just a small sample. The query could be run over hundreds of users when generating certain reporting.<br />
<br />
Any suggestions are appreciated!<br />
<br />
EXAMPLE:<br />
<br />
SELECT a.UserID<br />
FROM records AS a INNER JOIN records AS b<br />
WHERE a.UserID = b.UserID<br />
AND a.TimeClass = b.TimeClass<br />
AND a.RecordID != b.RecordID<br />
AND a.ClockIn &lt;&gt; b.ClockOut<br />
AND a.ClockOut &lt;&gt; b.ClockIn<br />
AND ( a.ClockIn BETWEEN b.ClockIn AND b.ClockOut<br />
     OR a.ClockOut BETWEEN b.ClockIn AND b.ClockOut<br />
)<br />
AND a.UserID IN (1,37491,74806,73680,13179,13220)<br />
AND b.UserID IN (1,37491,74806,73680,13179,13220)<br />
<br />
<br />
EXPLAIN:<br />
<br />
*************************** 1. row ***************************<br />
           id: 1<br />
  select_type: SIMPLE<br />
        table: a<br />
         type: range<br />
possible_keys: ix_accrualsum,idx_recordalerts,idx_payroll_elligible,idx_overlappcheck,idx_hourlyreport,idx_hourlyreport3<br />
          key: idx_overlappcheck<br />
      key_len: 4<br />
          ref: NULL<br />
         rows: 3766<br />
        Extra: Using where; Using index<br />
*************************** 2. row ***************************<br />
           id: 1<br />
  select_type: SIMPLE<br />
        table: b<br />
         type: ref<br />
possible_keys: ix_accrualsum,idx_recordalerts,idx_payroll_elligible,idx_overlappcheck,idx_hourlyreport,idx_hourlyreport3<br />
          key: idx_overlappcheck<br />
      key_len: 5<br />
          ref: _beta.a.UserID,_beta.a.TimeClass<br />
         rows: 82<br />
        Extra: Using where; Using index<br />
<br />
INDEXES:<br />
*************************** 1. row ***************************<br />
        Table: records<br />
   Non_unique: 0<br />
     Key_name: PRIMARY<br />
 Seq_in_index: 1<br />
  Column_name: RecordID<br />
    Collation: A<br />
  Cardinality: 8617349<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 2. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: ix_accrualsum<br />
 Seq_in_index: 1<br />
  Column_name: TimeClass<br />
    Collation: A<br />
  Cardinality: 17<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 3. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: ix_accrualsum<br />
 Seq_in_index: 2<br />
  Column_name: Approved<br />
    Collation: A<br />
  Cardinality: 1536<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 4. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_xhours<br />
 Seq_in_index: 1<br />
  Column_name: Paid<br />
    Collation: A<br />
  Cardinality: 17<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 5. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_xhours<br />
 Seq_in_index: 2<br />
  Column_name: TimeClass<br />
    Collation: A<br />
  Cardinality: 17<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 6. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_xhours<br />
 Seq_in_index: 3<br />
  Column_name: UserID<br />
    Collation: A<br />
  Cardinality: 331436<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 7. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_recordalerts<br />
 Seq_in_index: 1<br />
  Column_name: UserID<br />
    Collation: A<br />
  Cardinality: 22267<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 8. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_recordalerts<br />
 Seq_in_index: 2<br />
  Column_name: Approved<br />
    Collation: A<br />
  Cardinality: 37143<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 9. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_recordalerts<br />
 Seq_in_index: 3<br />
  Column_name: Paid<br />
    Collation: A<br />
  Cardinality: 44649<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 10. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_projectid<br />
 Seq_in_index: 1<br />
  Column_name: ProjectID<br />
    Collation: A<br />
  Cardinality: 2086<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 11. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_payroll_elligible<br />
 Seq_in_index: 1<br />
  Column_name: UserID<br />
    Collation: A<br />
  Cardinality: 47089<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 12. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_payroll_elligible<br />
 Seq_in_index: 2<br />
  Column_name: Paid<br />
    Collation: A<br />
  Cardinality: 62900<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 13. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_payroll_elligible<br />
 Seq_in_index: 3<br />
  Column_name: TimeClass<br />
    Collation: A<br />
  Cardinality: 103823<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 14. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_payroll_elligible<br />
 Seq_in_index: 4<br />
  Column_name: ClockIn<br />
    Collation: A<br />
  Cardinality: 8617349<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 15. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_overlappcheck<br />
 Seq_in_index: 1<br />
  Column_name: UserID<br />
    Collation: A<br />
  Cardinality: 92659<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 16. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_overlappcheck<br />
 Seq_in_index: 2<br />
  Column_name: TimeClass<br />
    Collation: A<br />
  Cardinality: 105089<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 17. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_overlappcheck<br />
 Seq_in_index: 3<br />
  Column_name: RecordID<br />
    Collation: A<br />
  Cardinality: 8617349<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 18. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_overlappcheck<br />
 Seq_in_index: 4<br />
  Column_name: ClockIn<br />
    Collation: A<br />
  Cardinality: 8617349<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 19. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_overlappcheck<br />
 Seq_in_index: 5<br />
  Column_name: ClockOut<br />
    Collation: A<br />
  Cardinality: 8617349<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 20. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport<br />
 Seq_in_index: 1<br />
  Column_name: UserID<br />
    Collation: A<br />
  Cardinality: 269292<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 21. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport<br />
 Seq_in_index: 2<br />
  Column_name: AccountCodeID<br />
    Collation: A<br />
  Cardinality: 359056<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 22. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport<br />
 Seq_in_index: 3<br />
  Column_name: TimeClass<br />
    Collation: A<br />
  Cardinality: 430867<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 23. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport<br />
 Seq_in_index: 4<br />
  Column_name: Signed<br />
    Collation: A<br />
  Cardinality: 453544<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 24. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport<br />
 Seq_in_index: 5<br />
  Column_name: Approved<br />
    Collation: A<br />
  Cardinality: 574489<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 25. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport<br />
 Seq_in_index: 6<br />
  Column_name: Paid<br />
    Collation: A<br />
  Cardinality: 718112<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 26. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport_acct<br />
 Seq_in_index: 1<br />
  Column_name: AccountCodeID<br />
    Collation: A<br />
  Cardinality: 74287<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 27. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport_acct<br />
 Seq_in_index: 2<br />
  Column_name: TimeClass<br />
    Collation: A<br />
  Cardinality: 94696<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 28. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport_acct<br />
 Seq_in_index: 3<br />
  Column_name: Signed<br />
    Collation: A<br />
  Cardinality: 94696<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 29. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport_acct<br />
 Seq_in_index: 4<br />
  Column_name: Approved<br />
    Collation: A<br />
  Cardinality: 116450<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 30. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport_acct<br />
 Seq_in_index: 5<br />
  Column_name: Paid<br />
    Collation: A<br />
  Cardinality: 123104<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 31. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport3<br />
 Seq_in_index: 1<br />
  Column_name: UserID<br />
    Collation: A<br />
  Cardinality: 84483<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 32. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport3<br />
 Seq_in_index: 2<br />
  Column_name: TimeClass<br />
    Collation: A<br />
  Cardinality: 126725<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment: <br />
*************************** 33. row ***************************<br />
        Table: records<br />
   Non_unique: 1<br />
     Key_name: idx_hourlyreport3<br />
 Seq_in_index: 3<br />
  Column_name: Paid<br />
    Collation: A<br />
  Cardinality: 165718<br />
     Sub_part: NULL<br />
       Packed: NULL<br />
         Null: <br />
   Index_type: BTREE<br />
      Comment: <br />
Index_comment:]]></description>
            <dc:creator>Anthony Galano</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Wed, 05 Jun 2013 05:49:07 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,585900,585900#msg-585900</guid>
            <title>Query optimization (8 replies)</title>
            <link>http://forums.mysql.com/read.php?115,585900,585900#msg-585900</link>
            <description><![CDATA[ I have such query:<br />
<br />
SELECT post_modified_gmt<br />
FROM wp_posts<br />
WHERE post_status =  'publish'<br />
AND post_type<br />
IN (<br />
 'post',  'page',  'attachment',  'topic'<br />
)<br />
ORDER BY post_date DESC <br />
LIMIT 1<br />
<br />
there is composite index on post_type,post_status,post_date columns but mysql uses filesort which dramaticly slows down this query execution. Is there any way to speed up this query?]]></description>
            <dc:creator>Jan Kowalski</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Wed, 22 May 2013 14:08:50 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,585323,585323#msg-585323</guid>
            <title>MySQL Optimizer:  When is a Subquery Executed? (no replies)</title>
            <link>http://forums.mysql.com/read.php?115,585323,585323#msg-585323</link>
            <description><![CDATA[ MySQL Optimizer:  When is a Subquery Executed?<br />
<a href="http://oysteing.blogspot.com/2013/05/when-is-subquery-executed.html"  rel="nofollow">http://oysteing.blogspot.com/2013/05/when-is-subquery-executed.html</a>]]></description>
            <dc:creator>Edwin Desouza</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Thu, 02 May 2013 16:05:23 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,581066,581066#msg-581066</guid>
            <title>Index optimized left join with group by (1 reply)</title>
            <link>http://forums.mysql.com/read.php?115,581066,581066#msg-581066</link>
            <description><![CDATA[ mysql&gt; explain select app_id from app_devs group by app_id;<br />
+----+-------------+----------+-------+---------------+---------+---------+------+-------+--------------------------+<br />
| id | select_type | table    | type  | possible_keys | key     | key_len | ref  | rows  | Extra                    |<br />
+----+-------------+----------+-------+---------------+---------+---------+------+-------+--------------------------+<br />
|  1 | SIMPLE      | app_devs | range | NULL          | PRIMARY | 2       | NULL | 32135 | Using index for group-by |<br />
+----+-------------+----------+-------+---------------+---------+---------+------+-------+--------------------------+<br />
<br />
mysql&gt; explain select app_id, name from app_devs left join apps on apps.id = app_id group by app_id;<br />
+----+-------------+----------+--------+---------------+---------+---------+--------------------------------+----------+-------------+<br />
| id | select_type | table    | type   | possible_keys | key     | key_len | ref                            | rows     | Extra       |<br />
+----+-------------+----------+--------+---------------+---------+---------+--------------------------------+----------+-------------+<br />
|  1 | SIMPLE      | app_devs | index  | NULL          | PRIMARY | 6       | NULL                           | 32905483 | Using index |<br />
|  1 | SIMPLE      | apps     | eq_ref | PRIMARY       | PRIMARY | 2       | fluik_services.app_devs.app_id |        1 |             |<br />
+----+-------------+----------+--------+---------------+---------+---------+--------------------------------+----------+-------------+<br />
<br />
Is there any way to perform left join to retrieve group by with left join that will use 'Using index for group-by'?<br />
Personally i found that using subquery can many times give what you want from query optimizer, but maybe there is some cleaner/better way to prevent full table scan?<br />
<br />
Possible subquery solution below:<br />
<br />
mysql&gt; explain select id, name from (select app_id as id, dev_id from app_devs group by app_id) as iq left join apps using (id);<br />
+----+-------------+------------+--------+---------------+---------+---------+-------+-------+--------------------------+<br />
| id | select_type | table      | type   | possible_keys | key     | key_len | ref   | rows  | Extra                    |<br />
+----+-------------+------------+--------+---------------+---------+---------+-------+-------+--------------------------+<br />
|  1 | PRIMARY     | &lt;derived2&gt; | ALL    | NULL          | NULL    | NULL    | NULL  |   125 |                          |<br />
|  1 | PRIMARY     | apps       | eq_ref | PRIMARY       | PRIMARY | 2       | iq.id |     1 |                          |<br />
|  2 | DERIVED     | app_devs   | range  | NULL          | PRIMARY | 2       | NULL  | 32135 | Using index for group-by |<br />
+----+-------------+------------+--------+---------------+---------+---------+-------+-------+--------------------------+<br />
<br />
Simplified table structure below:<br />
<br />
mysql&gt; show create table app_devs;<br />
  `app_id` smallint(5) unsigned NOT NULL,<br />
  `dev_id` int(10) unsigned NOT NULL,<br />
  `created_at` int(11) NOT NULL,<br />
  `updated_at` int(11) NOT NULL,<br />
  PRIMARY KEY (`app_id`,`dev_id`)<br />
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin |<br />
<br />
mysql&gt; show create table apps;<br />
  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,<br />
  `name` varchar(63) COLLATE utf8_bin NOT NULL,<br />
  PRIMARY KEY (`id`),<br />
  UNIQUE KEY `name_UNIQUE` (`name`)<br />
) ENGINE=InnoDB AUTO_INCREMENT=178 DEFAULT CHARSET=utf8 COLLATE=utf8_bin |]]></description>
            <dc:creator>Michal Kurgan</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 12 Mar 2013 10:16:52 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,578150,578150#msg-578150</guid>
            <title>MySQL 5.6:  IN Subqueries Are Optimized away (no replies)</title>
            <link>http://forums.mysql.com/read.php?115,578150,578150#msg-578150</link>
            <description><![CDATA[ MySQL 5.6:  IN Subqueries Are Optimized away<br />
<a href="https://blog.mozilla.org/it/2013/01/29/in-subqueries-in-mysql-5-6-are-optimized-away/"  rel="nofollow">https://blog.mozilla.org/it/2013/01/29/in-subqueries-in-mysql-5-6-are-optimized-away/</a>]]></description>
            <dc:creator>Edwin Desouza</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 29 Jan 2013 19:08:52 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,578144,578144#msg-578144</guid>
            <title>Very slow query, help please (3 replies)</title>
            <link>http://forums.mysql.com/read.php?115,578144,578144#msg-578144</link>
            <description><![CDATA[ Hello everyone.<br />
<br />
I have a very slow query (33.1319 seconds) and I don't know if there is a solution for this:<br />
<br />
<pre class="bbcode">
select proveidors_treballadors.id_prov_treb, nom, coalesce(fac,0) from proveidors_treballadors
left join (select id_prov_treb, ROUND((sum(materials+stock)),2) as fac from albarans 
left join (select id_albara, sum(quantitat*multiplicatiu) as materials from comandes_albarans_families group by id_albara)
    T1 on (albarans.id_albara=T1.id_albara)
left join (select id_albara, sum(quantitat*multiplicatiu) as stock from albarans_families group by id_albara)
    T2 on (albarans.id_albara=T2.id_albara) 
group by id_prov_treb)
T3 on (proveidors_treballadors.id_prov_treb=T3.id_prov_treb)
where tipus_prov_treb = 'proveidor';</pre>
<br />
The query explain is<br />
<br />
<img src="http://i48.tinypic.com/29poq38.png" class="bbcode" border="0" /><br />
<br />
And design for data base, the tables are in yellow color:<br />
<br />
<img src="http://i50.tinypic.com/1cayt.png" class="bbcode" border="0" /><br />
<br />
Thank you!]]></description>
            <dc:creator>Jaume Roca</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Wed, 30 Jan 2013 15:05:37 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,577795,577795#msg-577795</guid>
            <title>Select last row that is less than or equal to a date (20 replies)</title>
            <link>http://forums.mysql.com/read.php?115,577795,577795#msg-577795</link>
            <description><![CDATA[ I have a table with an index on a date. I want to get the last row<br />
whose date is less than or equal to a certain date. I would hope that<br />
MySQL could do this and only read one row. However, looking at the<br />
output of the &quot;explain&quot;, I'm not sure what MySQL is doing. Is MySQL<br />
reading more than one row, and if so, can the query be sped up? This<br />
is with MySQL 5.5.29. Here is the table:<br />
<br />
create table History (<br />
HistoryEvent        integer  unsigned not null, # EventID<br />
HistoryPlayer       integer  unsigned not null, # PlayerID<br />
HistoryDate         date              not null,<br />
HistoryReportID     integer           not null,<br />
HistoryInitialMean  smallint unsigned not null,<br />
HistoryInitialStDev smallint unsigned not null,<br />
HistoryFinalMean    smallint unsigned not null,<br />
HistoryFinalStDev   smallint unsigned not null,<br />
primary key                ( HistoryEvent,  HistoryPlayer ),<br />
unique index EventReportID ( HistoryEvent,  HistoryReportID ),<br />
index EventInitialMean     ( HistoryEvent,  HistoryInitialMean ),<br />
index EventFinalMean       ( HistoryEvent,  HistoryFinalMean ),<br />
index PlayerDate           ( HistoryPlayer, HistoryDate ) )<br />
default character set latin1 collate latin1_german1_ci pack_keys=1 engine=MyISAM;<br />
<br />
Here is the query and the output from &quot;explain&quot;:<br />
<br />
explain extended select * from History where HistoryPlayer = 59161 and<br />
HistoryDate &lt;= '2012-01-01' order by HistoryDate desc limit 0,1<br />
<br />
&quot;id&quot;,&quot;select_type&quot;,&quot;table&quot;,&quot;type&quot;,&quot;possible_keys&quot;,&quot;key&quot;,&quot;key_len&quot;,&quot;ref&quot;,&quot;rows&quot;,&quot;filtered&quot;,&quot;Extra&quot;<br />
1,&quot;SIMPLE&quot;,&quot;History&quot;,&quot;range&quot;,&quot;PlayerDate&quot;,&quot;PlayerDate&quot;,&quot;7&quot;,&quot;&quot;,67,100.00,&quot;Using where&quot;<br />
<br />
This one retrieves many rows, but the output from &quot;explain&quot; is the<br />
same:<br />
<br />
explain extended select * from History where HistoryPlayer = 59161 and<br />
HistoryDate &lt;= '2012-01-01' order by HistoryDate desc<br />
<br />
&quot;id&quot;,&quot;select_type&quot;,&quot;table&quot;,&quot;type&quot;,&quot;possible_keys&quot;,&quot;key&quot;,&quot;key_len&quot;,&quot;ref&quot;,&quot;rows&quot;,&quot;filtered&quot;,&quot;Extra&quot;<br />
1,&quot;SIMPLE&quot;,&quot;History&quot;,&quot;range&quot;,&quot;PlayerDate&quot;,&quot;PlayerDate&quot;,&quot;7&quot;,&quot;&quot;,67,100.00,&quot;Using where&quot;<br />
<br />
This one checks for a specific date, and &quot;explain&quot; says it will only<br />
read one row:<br />
<br />
explain extended select * from History where HistoryPlayer = 59161 and<br />
HistoryDate = '2012-01-01' order by HistoryDate desc limit 0,1<br />
<br />
&quot;id&quot;,&quot;select_type&quot;,&quot;table&quot;,&quot;type&quot;,&quot;possible_keys&quot;,&quot;key&quot;,&quot;key_len&quot;,&quot;ref&quot;,&quot;rows&quot;,&quot;filtered&quot;,&quot;Extra&quot;<br />
1,&quot;SIMPLE&quot;,&quot;History&quot;,&quot;ref&quot;,&quot;PlayerDate&quot;,&quot;PlayerDate&quot;,&quot;7&quot;,&quot;const,const&quot;,1,100.00,&quot;&quot;<br />
<br />
Here are the first two queries with a different value of<br />
HistoryPlayer:<br />
<br />
explain extended select * from History where HistoryPlayer = 59185 and<br />
HistoryDate &lt;= '2012-01-01' order by HistoryDate desc limit 0,1<br />
<br />
&quot;id&quot;,&quot;select_type&quot;,&quot;table&quot;,&quot;type&quot;,&quot;possible_keys&quot;,&quot;key&quot;,&quot;key_len&quot;,&quot;ref&quot;,&quot;rows&quot;,&quot;filtered&quot;,&quot;Extra&quot;<br />
1,&quot;SIMPLE&quot;,&quot;History&quot;,&quot;range&quot;,&quot;PlayerDate&quot;,&quot;PlayerDate&quot;,&quot;7&quot;,&quot;&quot;,29,100.00,&quot;Using where&quot;<br />
<br />
explain extended select * from History where HistoryPlayer = 59185 and<br />
HistoryDate &lt;= '2012-01-01' order by HistoryDate desc<br />
<br />
&quot;id&quot;,&quot;select_type&quot;,&quot;table&quot;,&quot;type&quot;,&quot;possible_keys&quot;,&quot;key&quot;,&quot;key_len&quot;,&quot;ref&quot;,&quot;rows&quot;,&quot;filtered&quot;,&quot;Extra&quot;<br />
1,&quot;SIMPLE&quot;,&quot;History&quot;,&quot;range&quot;,&quot;PlayerDate&quot;,&quot;PlayerDate&quot;,&quot;7&quot;,&quot;&quot;,29,100.00,&quot;Using where&quot;]]></description>
            <dc:creator>David Marcus</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Sun, 03 Feb 2013 22:15:51 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,577741,577741#msg-577741</guid>
            <title>New EXPLAIN Features in MySQL 5.6 – FORMAT=JSON actually adds more information! (no replies)</title>
            <link>http://forums.mysql.com/read.php?115,577741,577741#msg-577741</link>
            <description><![CDATA[ <a href="https://blog.mozilla.org/it/2013/01/22/new-explain-features-in-mysql-5-6-formatjson-actually-adds-more-information/"  rel="nofollow">https://blog.mozilla.org/it/2013/01/22/new-explain-features-in-mysql-5-6-formatjson-actually-adds-more-information/</a>]]></description>
            <dc:creator>Edwin Desouza</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 22 Jan 2013 23:58:49 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,577695,577695#msg-577695</guid>
            <title>CPU load very very high  !!!!, Please assist !! (1 reply)</title>
            <link>http://forums.mysql.com/read.php?115,577695,577695#msg-577695</link>
            <description><![CDATA[ Hello All<br />
<br />
My MySQL server hard configuration is as follows :-<br />
<br />
CentOS 5.8<br />
Dual Quad Core Processor<br />
3 GB ram<br />
MySQL  Ver 14.14 Distrib 5.1.61<br />
<br />
It's Stock Market website, Concurrent connections reach to 200 and the CPU usage reach 90% + <br />
<br />
When i run the command &quot;show processlist&quot; i get &quot;88 Rows in set&quot; or more.<br />
<br />
Most of the queries that we seee in the process list is &quot;SELECT vtiger_contactdetails.firstname &quot; statement !!!!!<br />
<br />
The client is worried about the CPU load reaching that high. How can i optimize my server to sever the above SELECT query in the least amount of time and server maximum user request.<br />
<br />
I am attaching along with this mail my sql configuration file for every one's reference for suggestion,<br />
<br />
Thank you,<br />
<br />
Since the board DOES NOT support attachment, i am pasting my configuration  file here in this post. <br />
<br />
PLEASE ACCEPT MY APOLOGIES !!!!<br />
<br />
========================<br />
      [mysqld]<br />
      2 datadir=/var/lib/mysql<br />
      3 socket=/var/lib/mysql/mysql.sock<br />
      4 user=mysql<br />
      5<br />
      6 server-id=1<br />
      7 #replicate-same-server-id=0<br />
      8 log-bin=newcrmdb1-bin<br />
      9 #binlog_do_db=crmdb<br />
     10 binlog_do_db=newcrmdb<br />
     11 binlog-ignore-db=mysql,test<br />
     12 #replicate_do_db=crmdb<br />
     13 #replicate_do_db=newcrmdb<br />
     14 #auto-increment-increment = 3<br />
     15 #auto-increment-offset = 1<br />
     16 #log-slave-updates<br />
     17<br />
     18 skip_name_resolve<br />
     19<br />
     20 #master-host = 192.168.0.203<br />
     21 #master-user = replication<br />
     22 #master-password = rplpassword<br />
     23 #master-port = 3306<br />
     24<br />
     25 innodb_flush_log_at_trx_commit=0<br />
     26 innodb_flush_method=O_DIRECT<br />
     27 sync_binlog=0<br />
     28 slave-skip-errors = 1062<br />
     29<br />
     30 back_log = 75<br />
     31 # skip-innodb<br />
     32 max_connections = 100<br />
     33 #thread_stack= 150M<br />
     34 key_buffer = 256M<br />
     35 key_buffer_size = 256M<br />
     36 myisam_sort_buffer_size = 16M<br />
     37 join_buffer_size = 4M<br />
     38 read_buffer_size = 16M<br />
     39 sort_buffer_size = 8M<br />
     40 table_cache = 1024<br />
     41 table_definition_cache = 4800<br />
     42 thread_cache_size = 128<br />
     43 wait_timeout = 100<br />
     44 connect_timeout = 60<br />
     45 tmp_table_size = 300M<br />
     46 max_heap_table_size = 300M<br />
     47 max_allowed_packet = 64M<br />
     48 #max_connect_errors = 10000<br />
     49 read_rnd_buffer_size = 8M<br />
     50 bulk_insert_buffer_size = 8M<br />
     51 query_cache_size = 256M<br />
     52 query_cache_limit = 4M<br />
     53 query_cache_type = 1<br />
     54 query_prealloc_size = 65536<br />
     55 query_alloc_block_size = 131072<br />
     56 default-storage-engine = InnoDB<br />
     57 innodb_buffer_pool_size = 2G<br />
     58 #innodb_log_file_size = 768M #25% of pool size<br />
     59 innodb_lock_wait_timeout = 120<br />
     60 innodb_use_sys_malloc = 0<br />
     61 long_query_time = 1<br />
     62 log-slow-queries = /var/log/mysql-slow-query.log<br />
     63<br />
     64 # Default to using old password format for compatibility with mysql 3.x<br />
     65 # clients (those using the mysqlclient10 compatibility package).<br />
     66 #old_passwords=1<br />
     67<br />
     68 # Disabling symbolic-links is recommended to prevent assorted security risks;<br />
     69 # to do so, uncomment this line:<br />
     70 # symbolic-links=0<br />
==================]]></description>
            <dc:creator>Sayed Ali</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Wed, 23 Jan 2013 05:32:25 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,577246,577246#msg-577246</guid>
            <title>mysql subquery query optimization question (1 reply)</title>
            <link>http://forums.mysql.com/read.php?115,577246,577246#msg-577246</link>
            <description><![CDATA[ We have a MySQL table that has approx. 1 million records. We recently upgraded our custom application to use Microsoft Entity Framework (EF), which abstracts out the datastore (in our case MySQL). When our application looks up a single record from the table, I noticed the EF issues a query like the following.<br />
<br />
select some_alias.* from (Select * from MyTable) as some_alias where some_alias.key = 'some_key'<br />
<br />
instead of<br />
<br />
select * from MyTable where key = 'some_key'<br />
<br />
The problem is that the first query takes more than 40 seconds to execute while the second query takes 15 milliseconds.<br />
<br />
At first I thought it was some kind of bug in EF for constructing the query this way. After further research, however, it turned out that the first query is as fast as the second query when using other database engines (so far tested on Oracle and MS SQL Server) so I can't blame EF entirely. :(<br />
<br />
My first question is why is the first query much slower than the second one in MySQL? Is it some kind of an optimizer issue? <br />
<br />
My second question is is there something I can do from the MySQL side to make the first query as fast as the second one? The reason I ask is because I've exhausted every possibility I could think of to address the issue from the application code side but have found no solution/workaround.<br />
<br />
Any suggestion/assistance would be greatly appreciated!]]></description>
            <dc:creator>Yong Yim</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Sun, 13 Jan 2013 17:30:51 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,576920,576920#msg-576920</guid>
            <title>Create a New Datatype (1 reply)</title>
            <link>http://forums.mysql.com/read.php?115,576920,576920#msg-576920</link>
            <description><![CDATA[ I would like to create a new datatype to the MySQL database.  I program best using C# in a Visual Studio programming environment.<br />
<br />
The type I would like to create is what could be called an interval type and would look like this:<br />
<br />
[1/1/2012:1/10/2012]<br />
<br />
I would also like to create operators on the type, so operations like the one below could be done:<br />
<br />
set @interval1 := [1/1/2012:1/10/2012]<br />
set @interval2 := [1/5/2012:1/15/2012]<br />
<br />
select @interval1 overlaps @interval2<br />
<br />
The result set of the select above that uses the type interval with the operator overlaps would be:<br />
<br />
[1/5/2012:1/10/2012]<br />
<br />
along with other operators on the interval type.  <br />
<br />
I would like to expand the SQL of MySQL to support my new type and the operators I develop with it.<br />
<br />
My question is, is this possible?  I would like to stay within my area of programming expertise, that is C# in a Visual Studio environment.<br />
<br />
If possible, how large an effort would this be?  Although I am most comfortable in a Visual Studio environment using C#, what would be the best environment, if programming expertise was not an issue?<br />
<br />
Thank you]]></description>
            <dc:creator>Andy Gurzynski</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 08 Jan 2013 05:01:14 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,576862,576862#msg-576862</guid>
            <title>Can we expect an enhancement for derived table merge optimization? (7 replies)</title>
            <link>http://forums.mysql.com/read.php?115,576862,576862#msg-576862</link>
            <description><![CDATA[ In MySql 5.5 (and 5.6), derived tables are materialized before any helpful where clauses on the containing query are merged in.<br />
<br />
For example:<br />
<br />
select 'briefing_story_id '<br />
from (select briefing_story_id, created_user_id<br />
      from briefing_story where briefing_story.story_type = 'CLIP') as inner_select<br />
where inner_select.created_user_id = 12;<br />
<br />
expands the derived table using only the where clause presented on derived table:  briefing_story.story_type = 'CLIP'. Often times, the surrounding query adds on a much better filter that might lead to an index being the obvious path: inner_select.created_user_id = 12.<br />
<br />
MariaDb claims to already have this optimization, and calls it &quot;derived table merge&quot;.<br />
<br />
Strangely, it seems as though MySql is already handling this same concept when selecting from a view (which seems conceptually like the same problem, but what do I know.) The view is not materialized- instead, any where clauses in the view are combined with the where clauses of the containing query.<br />
<br />
My question is really twofold: <br />
<br />
a) Am I correct that this feature does not currently exist in any MySql version? (I tested in 5.5.16 and 5.6.7 and neither merged the where clause.)<br />
b) Is this feature anywhere in the development roadmap, and if so, what is the best guess of when (date and or version) it will be included in MySql?<br />
<br />
As a side-note, I'm asking asking because we're using an O-R Mapping Tool (Microsoft's Entity Framework) combined with the MySql Connector. Together, they  make heavy use of derived tables in their generated SQL.<br />
 <br />
<br />
Thanks greatly.]]></description>
            <dc:creator>Michael Hogue</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 15 Jan 2013 12:15:28 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,576425,576425#msg-576425</guid>
            <title>MySQL Optimizer: InnoDB extended secondary keys (no replies)</title>
            <link>http://forums.mysql.com/read.php?115,576425,576425#msg-576425</link>
            <description><![CDATA[ MySQL Optimizer: InnoDB extended secondary keys<br />
<a href="http://glukhsv.blogspot.co.uk/2012/12/innodb-extended-secondary-keys.html"  rel="nofollow">http://glukhsv.blogspot.co.uk/2012/12/innodb-extended-secondary-keys.html</a>]]></description>
            <dc:creator>Edwin Desouza</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Fri, 21 Dec 2012 18:12:26 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,576261,576261#msg-576261</guid>
            <title>MySQL Optimizer:  Favorite features in MySQL 5.6 (no replies)</title>
            <link>http://forums.mysql.com/read.php?115,576261,576261#msg-576261</link>
            <description><![CDATA[ MySQL Optimizer:  Favorite features in MySQL 5.6<br />
<a href="http://jorgenloland.blogspot.com/2012/12/favorite-mysql-56-features-optimizer.html"  rel="nofollow">http://jorgenloland.blogspot.com/2012/12/favorite-mysql-56-features-optimizer.html</a>]]></description>
            <dc:creator>Edwin Desouza</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 18 Dec 2012 17:38:13 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,575721,575721#msg-575721</guid>
            <title>How to best optimize MYSQL Database (2 replies)</title>
            <link>http://forums.mysql.com/read.php?115,575721,575721#msg-575721</link>
            <description><![CDATA[ Few days ago my site i.e. <a href="http://www.funbench.com"  rel="nofollow">http://www.funbench.com</a> got hacked by the hackers, but after getting it back, some codes have remained in the database. I have tried many pluggins to get rid of these codes, but i couldn't find the best one for this purpose. Can you tell me any best way to get my site error free after hacking?]]></description>
            <dc:creator>Muhammad Usman</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Mon, 14 Jan 2013 10:03:16 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,575412,575412#msg-575412</guid>
            <title>Optimizer for innodb does not reduce &quot;data_free&quot; (1 reply)</title>
            <link>http://forums.mysql.com/read.php?115,575412,575412#msg-575412</link>
            <description><![CDATA[ System-specs:<br />
-- MySQL Version 9.10 Distrib 5.5.28<br />
-- Fresh installation on SLES 11 SP 2 (64bit) rpm<br />
-- innodb_file_per_table<br />
<br />
Problem:<br />
table status of innodb tables shows &quot;data_free=4194304&quot; for several tables of a freshly importet database on a freshly installed database-server! (which means fragmentation?!)<br />
<br />
optimize table [tablename] wont change anything - tables are being recreated but data_free value is the same as before.<br />
<br />
<br />
Since i've set &quot;innodb_file_per_table&quot;, i thought data would be stored in the specific tables directory instead of the shared datafile?!<br />
<br />
Why can have multiple tables have exactly the same value in data_free?<br />
Why is optimize table not working in that case?<br />
<br />
Any clarification would be much appreciated.]]></description>
            <dc:creator>Sebastian Schött</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Sat, 08 Dec 2012 19:33:22 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,572908,572908#msg-572908</guid>
            <title>Complex query - need advise (3 replies)</title>
            <link>http://forums.mysql.com/read.php?115,572908,572908#msg-572908</link>
            <description><![CDATA[ Hi guys,<br />
<br />
I need some advice, aggregates across multiple joins, query is running horribly slow on a small amazon mysql RDS DB. Any ideas?<br />
<br />
SELECT 'Name publisher' AS Publisher,<br />
       t.`Campaign Name` AS CampaignName,<br />
       c.Impressions AS ProviderImpressions,<br />
       c.Clicks AS ProviderClicks,<br />
       t.`Date` AS SearchDate,<br />
       t.Impressions AS TotalServedImpressions,<br />
       t.Clicks AS TotalClicks,<br />
       ROUND(t.GrossMediaCost, 2) AS GrossMediaCost,<br />
       ROUND(((t.Clicks / t.Impressions) * 100), 3) AS CTR,<br />
       ROUND((((c.Impressions - t.Impressions) / t.Impressions) * 100), 2) AS PercImp,<br />
       ROUND((((c.Clicks - t.Clicks) / t.Clicks) * 100), 2) AS CalcClicks,<br />
       ROUND((t.GrossMediaCost / (c.Impressions / 1000)), 2) AS ECPM,<br />
       ROUND((t.GrossMediaCost / c.Clicks), 5) AS ECPC      <br />
  FROM (SELECT sum(Impressions) AS Impressions, sum(Clicks) AS Clicks<br />
        FROM Delivery<br />
        WHERE AdID IN<br />
                    (SELECT distinct d.AdID<br />
                     FROM MetaData m, Delivery d, Media mm<br />
                     WHERE     m.AdID = d.AdID and m.PlacementID = mm.`Placement ID 3PAS`<br />
                          AND m.CampaignName = 'campaign name'<br />
                          AND date_format(str_to_date(mm.`Date`, '%d-%m-%Y'), '%Y-%m-%d') = '2012-10-29')<br />
        ) c,<br />
       (SELECT `Campaign Name`, `Date`, sum(Impressions) AS Impressions, sum(Clicks) AS Clicks, sum(`Gross Media Cost`) AS GrossMediaCost<br />
        FROM Media<br />
        WHERE`Placement ID 3PAS` IN<br />
                                   (SELECT distinct mm.`Placement ID 3PAS`<br />
                                    FROM  MetaData m, Media mm<br />
                                    WHERE m.PlacementID = mm.`Placement ID 3PAS`<br />
                                    AND m.CampaignName = 'campaign name'<br />
                                    AND date_format(str_to_date(mm.`Date`, '%d-%m-%Y'), '%Y-%m-%d') = '2012-10-29')<br />
        ) t<br />
GROUP BY CampaignName, SearchDate<br />
ORDER BY CampaignName, SearchDate]]></description>
            <dc:creator>chris boer</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Mon, 05 Nov 2012 17:12:19 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,572040,572040#msg-572040</guid>
            <title>Follow up on &quot;Query Execution Plan&quot; (2 replies)</title>
            <link>http://forums.mysql.com/read.php?115,572040,572040#msg-572040</link>
            <description><![CDATA[ I posted a topic about five months ago, but I now see it is closed. I want to add some additional information in case anyone is interested. The following link takes you to the original post.<br />
<br />
<a href="http://forums.mysql.com/read.php?115,532367,532367#msg-532367"  rel="nofollow">http://forums.mysql.com/read.php?115,532367,532367#msg-532367</a><br />
<br />
As discussed before, I implemented a work around that is only somewhat satisfactory; using an in general slower more complex query to get rid of those rare catistrophic execution times.I decided to revisit this topic and discovered something interesting.<br />
<br />
I chose a table that was behaving as a &quot;slow fetch&quot;, using the original implementation. As a reminder, the query is as follows.<br />
<br />
select * from &lt;table&gt; where time &lt;= &lt;time&gt; order by time desc limit 1<br />
<br />
I noticed that the choice of execution plan depended on the value of time supplied in the query. I wrote a test program to ask the server for the execution plan of the query above, but using a time ranging from the begining of data to the end. Remember that the data table rows are timestamped value samples of experimental data, with the time as primary index.<br />
<br />
The output of the test program was the time used in the &quot;explain&quot;, converted to human friendly for the test output, and the execution plan chosen by the server. My time step for this test was one day. The result was that the execution plan started with 'range' and continued to a point in time where it switched to 'index'; continuing with the latter until the end. I have included the result below, but replaced most of the redundant lines with the '...'.<br />
<br />
2009-11-11 03:59:17 range<br />
2009-11-12 03:59:17 range<br />
2009-11-13 03:59:17 range<br />
         ...<br />
2012-01-07 03:59:17 range<br />
2012-01-08 03:59:17 range<br />
2012-01-09 03:59:17 range<br />
2012-01-10 03:59:17 index<br />
2012-01-11 03:59:17 index<br />
2012-01-12 03:59:17 index<br />
         ...<br />
2012-10-22 04:59:17 index<br />
2012-10-23 04:59:17 index<br />
2012-10-24 04:59:17 index<br />
<br />
The server's choice of plan depends on where the requested time falls within the table index. Fetching older data uses the 'range' plan and is much faster.]]></description>
            <dc:creator>Chris Slominski</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Thu, 25 Oct 2012 17:14:48 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,570943,570943#msg-570943</guid>
            <title>JOIN query too slow (2 replies)</title>
            <link>http://forums.mysql.com/read.php?115,570943,570943#msg-570943</link>
            <description><![CDATA[ Hi all!<br />
<br />
I'm trying to optimize some of my queries, as this database I'm working on is getting big.<br />
<br />
I've a table with this structure:<br />
<br />
mysql&gt; SHOW CREATE TABLE Personas_experiencias;<br />
+-----------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br />
| Table                 | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |<br />
+-----------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br />
| Personas_experiencias | CREATE TABLE `Personas_experiencias` (<br />
  `id` bigint(20) NOT NULL AUTO_INCREMENT,<br />
  `IdPersona` int(11) NOT NULL,<br />
  `Empresa` varchar(150) COLLATE latin1_spanish_ci NOT NULL,<br />
  `Puesto` varchar(4) COLLATE latin1_spanish_ci NOT NULL,<br />
  `Funcion` varchar(150) COLLATE latin1_spanish_ci DEFAULT NULL,<br />
  `Inicio` date DEFAULT NULL,<br />
  `Fin` date DEFAULT NULL,<br />
  `Actual` tinyint(4) DEFAULT '0',<br />
  PRIMARY KEY (`id`),<br />
  KEY `IdPersona` (`IdPersona`)<br />
) ENGINE=MyISAM AUTO_INCREMENT=5728 DEFAULT CHARSET=latin1 COLLATE=latin1_spanish_ci |<br />
+-----------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+<br />
1 row in set (0.14 sec)<br />
<br />
The thing is I need to do many JOINs on this table over itself, in order to look for several parameters in the same query. So, the basic query I'm trying to optimize is this:<br />
<br />
SELECT `Personas`.`IdPersona` AS `id`,`Personas`.`NIF` AS `DNICIF`,`Personas`.`Nombre` AS `Nombre`,`Personas`.`Apellidos` AS `Apellidos`,`Personas`.`Email` AS `Email`,`Personas`.`Telefono` AS `OtrosDatos` <br />
FROM `Personas`, `Personas_experiencias` AS `Personas_experiencias0`,  `Personas_experiencias` AS `Personas_experiencias1`,  `Personas_experiencias` AS `Personas_experiencias2`,  `Personas_experiencias` AS `Personas_experiencias3` <br />
WHERE (`Personas`.`IdPersona` = `Personas_experiencias0`.`IdPersona`) AND (`Personas_experiencias0`.`IdPersona` = `Personas_experiencias1`.`IdPersona`) AND (`Personas_experiencias1`.`IdPersona` = `Personas_experiencias2`.`IdPersona`) AND (`Personas_experiencias2`.`IdPersona` = `Personas_experiencias3`.`IdPersona`);<br />
<br />
Well, the EXPLAIN for this SELECT is the following:<br />
<br />
mysql&gt; EXPLAIN SELECT `Personas`.`IdPersona` AS `id`,`Personas`.`NIF` AS `DNICIF`,`Personas`.`Nombre` AS `Nombre`,`Personas`.`Apellidos` AS `Apellidos`,`Personas`.`Email` AS `Email`,`Personas`.`Telefono` AS `OtrosDatos` FROM `Personas`,      `Personas_experiencias` AS `Personas_experiencias0`,  `Personas_experiencias` AS `Personas_experiencias1`,  `Personas_experiencias` AS `Personas_experiencias2`,  `Personas_experiencias` AS `Personas_experiencias3` WHERE (`Personas`.`IdPersona` = `Personas_experiencias0`.`IdPersona`) AND (`Personas_experiencias0`.`IdPersona` = `Personas_experiencias1`.`IdPersona`) AND (`Personas_experiencias1`.`IdPersona` = `Personas_experiencias2`.`IdPersona`) AND (`Personas_experiencias2`.`IdPersona` = `Personas_experiencias3`.`IdPersona`);<br />
+----+-------------+------------------------+--------+---------------+-----------+---------+-----------------------------------------+------+--------------------------+<br />
| id | select_type | table                  | type   | possible_keys | key       | key_len | ref                                     | rows | Extra                    |<br />
+----+-------------+------------------------+--------+---------------+-----------+---------+-----------------------------------------+------+--------------------------+<br />
|  1 | SIMPLE      | Personas_experiencias0 | index  | IdPersona     | IdPersona | 4       | NULL                                    | 4980 | Using index              |<br />
|  1 | SIMPLE      | Personas               | eq_ref | PRIMARY       | PRIMARY   | 4       | qmn125.Personas_experiencias0.IdPersona |    1 |                          |<br />
|  1 | SIMPLE      | Personas_experiencias1 | ref    | IdPersona     | IdPersona | 4       | qmn125.Personas_experiencias0.IdPersona |    5 | Using index              |<br />
|  1 | SIMPLE      | Personas_experiencias2 | ref    | IdPersona     | IdPersona | 4       | qmn125.Personas_experiencias1.IdPersona |    5 | Using where; Using index |<br />
|  1 | SIMPLE      | Personas_experiencias3 | ref    | IdPersona     | IdPersona | 4       | qmn125.Personas.IdPersona               |    5 | Using where; Using index |<br />
+----+-------------+------------------------+--------+---------------+-----------+---------+-----------------------------------------+------+--------------------------+<br />
5 rows in set (0.03 sec)<br />
<br />
4980 rows are the total number of rows at Personas_experiencias. I think the main problem is the first row of the explain command, and it takes up to 1 minute and 30 seconds to execute (I'd need to reduce it to at least to the 1/3 of time!).<br />
<br />
Can someone advise how to improve that? I tried to define several indexes involving several columns but I can't find a way to reduce this!<br />
<br />
Thanks so much in advance!]]></description>
            <dc:creator>N. Kovac</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Wed, 17 Oct 2012 01:48:38 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,569510,569510#msg-569510</guid>
            <title>bulk update very slow (3 replies)</title>
            <link>http://forums.mysql.com/read.php?115,569510,569510#msg-569510</link>
            <description><![CDATA[ I have a update query, it runs very slow (take about 5 minutes), but if convert it to select query, it only take 30 seconds.<br />
<br />
This one take 5 minutes<br />
UPDATE scheduled_messages SET `batchID`='17' WHERE scheduled_time = '2012-09-12 15:00:00' AND status = 'scheduled' AND batchID IS NULL ORDER BY aggregatorID ASC,shortcodeID ASC LIMIT 1100<br />
<br />
This one only take 30 seconds.<br />
select * from scheduled_messages WHERE scheduled_time = '2012-09-12 15:00:00' AND status = 'scheduled' AND batchID IS NULL ORDER BY aggregatorID ASC,shortcodeID ASC LIMIT 1100<br />
<br />
 CREATE TABLE `scheduled_messages` (<br />
  `scheduled_message_id` bigint(20) NOT NULL AUTO_INCREMENT,<br />
  `batchID` int(11) DEFAULT NULL,<br />
  `subscriber_id` int(11) DEFAULT NULL,<br />
  `oneTime` tinyint(1) DEFAULT NULL,<br />
  `sendType` varchar(9) COLLATE utf8_unicode_ci DEFAULT NULL,<br />
  `message_type` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,<br />
  `message_text` tinytext COLLATE utf8_unicode_ci,<br />
  `scheduled_time` datetime DEFAULT NULL,<br />
  `status` tinytext COLLATE utf8_unicode_ci,<br />
  `aggregatorID` int(11) DEFAULT NULL,<br />
  `shortcodeID` int(11) DEFAULT NULL,<br />
  `retry_log_id` int(11) DEFAULT NULL,<br />
  PRIMARY KEY (`scheduled_message_id`),<br />
  KEY `idx_time` (`scheduled_time`),<br />
  KEY `idx_retry_log_id` (`retry_log_id`),<br />
  KEY `idx_subscriber_id` (`subscriber_id`),<br />
  KEY `batch` (`batchID`)<br />
) ENGINE=InnoDB AUTO_INCREMENT=189331034 DEFAULT CHARSET=utf8 COLLATE=utf8_unico<br />
de_ci |]]></description>
            <dc:creator>Zhijian chen</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Fri, 28 Sep 2012 02:19:51 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,569274,569274#msg-569274</guid>
            <title>Why Query Cache Actived Returns Wrong Results? (3 replies)</title>
            <link>http://forums.mysql.com/read.php?115,569274,569274#msg-569274</link>
            <description><![CDATA[ Hi.<br />
I need to do some queries to tables with records very big. So this takes a lot of time, so I active cache, to make things faster, but sometimes, I get wrong results, because sometimes the result is 0. If I do the same query, with cache disabled, I get the right results. Do I need to configure another parameter? I configure query_cache_size=1G. My table is MyISAM...<br />
Thanks]]></description>
            <dc:creator>Daniel Estrada</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 25 Sep 2012 05:43:36 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,568789,568789#msg-568789</guid>
            <title>Join? Union? I am so lost. (1 reply)</title>
            <link>http://forums.mysql.com/read.php?115,568789,568789#msg-568789</link>
            <description><![CDATA[ I have 2 tables. One with 20,000 entries the only with a few hundred.<br />
I need to group and order both tables by the dates and SUM the Debits and Credits in each.  (FYI settle is a date.)<br />
<br />
something like this:<br />
<br />
$query = &quot;SELECT  proj3_trades.settle, proj3_cash.date,<br />
          ROUND(( SUM(sale) - SUM(purch) ),0) as netTrades, <br />
	  ROUND(( SUM(credit) - SUM(debit) ),0) as netCashFlow<br />
	  FROM proj3_trades   LEFT  JOIN proj3_cash<br />
          ON proj3_trades.settle = proj3_cash.date<br />
	  GROUP BY proj3_trades.settle<br />
	  ORDER BY proj3_trades.settle ASC&quot;;<br />
<br />
I unfortunately no SQL guru. And if there is one out there - thank you VERY MUCH.<br />
good karma to all.<br />
Cheers.]]></description>
            <dc:creator>Hank Reardon</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 18 Sep 2012 13:48:32 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,568346,568346#msg-568346</guid>
            <title>How make indexes work with group by statement (2 replies)</title>
            <link>http://forums.mysql.com/read.php?115,568346,568346#msg-568346</link>
            <description><![CDATA[ Hi,<br />
<br />
Whenever I use group by statement with the fields that have an index on them, the index does not work especially when group by has more than one columns.<br />
<br />
e.g.<br />
<br />
explain select * from temp_table<br />
group by dt1,dt2;<br />
<br />
is there any solution for it?]]></description>
            <dc:creator>Adnan Raza</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Sun, 16 Sep 2012 04:34:43 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,567376,567376#msg-567376</guid>
            <title>Query Optimizer Problem - OrderBy - 5.0.51 to 5.5.27 (2 replies)</title>
            <link>http://forums.mysql.com/read.php?115,567376,567376#msg-567376</link>
            <description><![CDATA[ We are facing problems with the execution plan of queries that use an order by. With 5.0.51 an existing index was used, with 5.5 it is not used anymore. I created a very small example that shows the problem.<br />
<br />
Why the index is not used anymore with 5.5? When i use &quot;force index (testIndex)&quot; it works.<br />
<br />
<br />
With 5.0.51<br />
<br />
create database test;<br />
use test;<br />
create table test (id int primary key, a varchar(20), b varchar(30)) engine = innodb;<br />
explain select * from test order by a;<br />
create index testIndex on test(a);<br />
explain select * from test order by a;<br />
<br />
--&gt; Results in:<br />
<br />
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+<br />
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra          |<br />
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+<br />
|  1 | SIMPLE      | test  | ALL  | NULL          | NULL | NULL    | NULL |    1 | Using filesort | <br />
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+<br />
<br />
<br />
<br />
+----+-------------+-------+-------+---------------+-----------+---------+------+------+-------+<br />
| id | select_type | table | type  | possible_keys | key       | key_len | ref  | rows | Extra |<br />
+----+-------------+-------+-------+---------------+-----------+---------+------+------+-------+<br />
|  1 | SIMPLE      | test  | index | NULL          | testIndex | 63      | NULL |    1 |       | <br />
+----+-------------+-------+-------+---------------+-----------+---------+------+------+-------+<br />
<br />
<br />
<br />
<br />
============================<br />
<br />
<br />
<br />
With 5.5.27<br />
<br />
create database test;<br />
use test;<br />
create table test (id int primary key, a varchar(20), b varchar(30)) engine = innodb;<br />
explain select * from test order by a;<br />
create index testIndex on test(a);<br />
explain select * from test order by a;<br />
<br />
--&gt; Results in:<br />
<br />
<br />
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+<br />
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra          |<br />
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+<br />
|  1 | SIMPLE      | test  | ALL  | NULL          | NULL | NULL    | NULL |    1 | Using filesort |<br />
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+<br />
<br />
<br />
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+<br />
| id | select_type | table | type | possible_keys | key  | key_len | ref  | rows | Extra          |<br />
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+<br />
|  1 | SIMPLE      | test  | ALL  | NULL          | NULL | NULL    | NULL |    1 | Using filesort |<br />
+----+-------------+-------+------+---------------+------+---------+------+------+----------------+]]></description>
            <dc:creator>Dominik Bieringer</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Fri, 07 Sep 2012 04:42:12 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,566478,566478#msg-566478</guid>
            <title>optimize the query (5 replies)</title>
            <link>http://forums.mysql.com/read.php?115,566478,566478#msg-566478</link>
            <description><![CDATA[ select a.* from  left join BehaviourModel b on a.newcustid=b.newcustid and a.obsdate=b.obsdate where a.leadid like &quot;20120819%&quot;\G;<br />
<br />
Please give me the suggetion getting fast execution]]></description>
            <dc:creator>ch srinivas</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Thu, 30 Aug 2012 13:20:20 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,565870,565870#msg-565870</guid>
            <title>Order By Slows down Joins (1 reply)</title>
            <link>http://forums.mysql.com/read.php?115,565870,565870#msg-565870</link>
            <description><![CDATA[ Hello,<br />
<br />
I have problem with this query<br />
<br />
    SELECT *<br />
    FROM files f<br />
    LEFT JOIN xfiles x ON x.hash = f.bhash<br />
    LEFT JOIN cate c ON c.id = f.cate<br />
    LEFT JOIN users u ON u.id = f.user<br />
    LEFT JOIN userslev ul ON u.id_lev = ul.id<br />
    LEFT JOIN (<br />
    <br />
    SELECT DISTINCT x.hash, s.iis<br />
    FROM anno x<br />
    JOIN seb s ON s.iis = x.icc<br />
    WHERE x.le =0<br />
    AND (<br />
    x.eve =0<br />
    OR x.eve =2<br />
    )<br />
    GROUP BY  `x`.`hash`<br />
    ) AS tabel2 ON tabel2.hash = f.bhash<br />
    WHERE f.see + IFNULL( x.see, 0 ) + f.lee + IFNULL( x.lee, 0 ) &gt;0<br />
    ORDER BY f.added DESC<br />
<br />
Showing rows 0 - 29 ( 22,083 total, Query took 9.6523 sec)<br />
<br />
as you can see , it takes 9 sec !<br />
<br />
but without 'order by'<br />
<br />
    SELECT *<br />
    FROM files f<br />
    LEFT JOIN xfiles x ON x.hash = f.bhash<br />
    LEFT JOIN cate c ON c.id = f.cate<br />
    LEFT JOIN users u ON u.id = f.user<br />
    LEFT JOIN userslev ul ON u.id_lev = ul.id<br />
    LEFT JOIN (<br />
    <br />
    SELECT DISTINCT x.hash, s.iis<br />
    FROM anno x<br />
    JOIN seb s ON s.iis = x.icc<br />
    WHERE x.le =0<br />
    AND (<br />
    x.eve =0<br />
    OR x.eve =2<br />
    )<br />
    GROUP BY  `x`.`hash`<br />
    ) AS tabel2 ON tabel2.hash = f.bhash<br />
    WHERE f.see + IFNULL( x.see, 0 ) + f.lee + IFNULL( x.lee, 0 ) &gt;0<br />
<br />
<br />
Showing rows 0 - 29 ( 22,083 total, Query took 0.0241 sec)<br />
<br />
only 0.0241 sec :)<br />
<br />
............<br />
<br />
is there a way to have ' order by' with good-time?<br />
<br />
............<br />
<br />
indexes:<br />
<br />
<br />
    Indexes: (files)<br />
    <br />
    Action	Keyname	Type	Unique	Packed	Column	Cardinality	Collation	Null	Comment<br />
     Edit	 Drop	PRIMARY	BTREE	Yes	No	ihash	27815	A		<br />
     Edit	 Drop	filename	BTREE	No	No	filename	27815	A		<br />
     Edit	 Drop	cate	BTREE	No	No	cate	45	A		<br />
     Edit	 Drop	user	BTREE	No	No	user	1264	A		<br />
     Edit	 Drop	bhash	BTREE	No	No	bhash (20)	27815	A		<br />
     Edit	 Drop	added	BTREE	No	No	added	27815	A		<br />
     Edit	 Drop	filename_2	FULLTEXT	No	No	filename	1			<br />
    <br />
    <br />
    <br />
    Indexes: (xfiles)<br />
    <br />
    Action	Keyname	Type	Unique	Packed	Column	Cardinality	Collation	Null	Comment<br />
     Edit	 Drop	PRIMARY	BTREE	Yes	No	id	8196	A		<br />
     Edit	 Drop	hash	BTREE	Yes	No	hash	8196	A		<br />
     Edit	 Drop	see	BTREE	No	No	see	37	A		<br />
     Edit	 Drop	leec	BTREE	No	No	lee25	A	<br />
    <br />
    <br />
    Indexes: (cate)<br />
    <br />
    Action	Keyname	Type	Unique	Packed	Column	Cardinality	Collation	Null	Comment<br />
     Edit	 Drop	PRIMARY	BTREE	Yes	No	id	51	A	<br />
     <br />
     <br />
    Indexes: (users)<br />
    <br />
    Action	Keyname	Type	Unique	Packed	Column	Cardinality	Collation	Null	Comment<br />
     Edit	 Drop	PRIMARY	BTREE	Yes	No	id	39776	A		<br />
     Edit	 Drop	username	BTREE	Yes	No	username	39776	A		<br />
     Edit	 Drop	id_lev	BTREE	No	No	id_lev	19	A		<br />
    <br />
     <br />
    Indexes: (userslev)<br />
    <br />
    Action	Keyname	Type	Unique	Packed	Column	Cardinality	Collation	Null	Comment<br />
     Edit	 Drop	base	BTREE	Yes	No	id	22	A		<br />
    <br />
    <br />
    Indexes: (anno)<br />
    <br />
    Action	Keyname	Type	Unique	Packed	Column	Cardinality	Collation	Null	Comment<br />
     Edit	 Drop	PRIMARY	BTREE	Yes	No	id	23636	A		<br />
     Edit	 Drop	icc	BTREE	No	No	icc	2626	A		<br />
     Edit	 Drop	eve	BTREE	No	No	eve	8	A		<br />
     Edit	 Drop	hash	BTREE	No	No	hash	5909	A		<br />
     Edit	 Drop	le	BTREE	No	No	le	875	A	<br />
    <br />
     <br />
    Indexes: (seb)<br />
    <br />
    Action	Keyname	Type	Unique	Packed	Column	Cardinality	Collation	Null	Comment<br />
     Edit	 Drop	PRIMARY	BTREE	Yes	No	id	58	A		<br />
     Edit	 Drop	iis	BTREE	Yes	No	iis	58	A	YES	<br />
<br />
<br />
EXPLAIN:<br />
<br />
    id	        select_type    	table   	type        	possible_keys   	key     	key_len     	ref     	rows	Extra<br />
    1           	PRIMARY	    f	        ALL         	NULL            	NULL     	NULL        	NULL    	27819	Using temporary; Using filesort<br />
    1           	PRIMARY 	x        	eq_ref      	hash            	hash     	20          	f.bhash 	1   	Using where<br />
    1           	PRIMARY 	c       	eq_ref      	PRIMARY         	PRIMARY  	4           	f.cate  	1	<br />
    1           	PRIMARY 	u       	eq_ref      	PRIMARY         	PRIMARY 	4           	f.user  	1	<br />
    1           	PRIMARY 	ul      	eq_ref      	base            	base    	4            	u.id_lev	1	<br />
    1           	PRIMARY 	&lt;derived2&gt;	ALL         	NULL            	NULL    	NULL         	NULL    	1176	<br />
    2           	DERIVED 	s       	index       	iis             	iis     	5           	NULL    	58   	Using index; Using temporary; Using filesort<br />
    2           	DERIVED 	x       	ref         	icc,eve,le      	icc     	4           	s.iis    	9	    Using where]]></description>
            <dc:creator>Sami BH</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Fri, 24 Aug 2012 02:56:04 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,565865,565865#msg-565865</guid>
            <title>CONCAT and Index in where clause (4 replies)</title>
            <link>http://forums.mysql.com/read.php?115,565865,565865#msg-565865</link>
            <description><![CDATA[ Hi, <br />
<br />
I've got a really slow query (which I can't change) using the concat function in the where clause.<br />
<br />
The query looks like : <br />
SELECT * from MyTABLE WHERE CONCAT(YEAR,'-',MONTH,'-',DAY) = '2012-08-21';<br />
<br />
Where 'YEAR', 'MONTH' and 'DAY' are three fields of type CHAR.<br />
<br />
I tried to add an index only on the column YEAR (I don't think an Index on the three columns would be usefull because of the CONCAT function).<br />
<br />
I can't get the index to be used in this case. I've seen some cases where there are types INT and CHAR in the CONCAT function, and so a function like CAST must be used to convert the INT type, but this is not my case.<br />
<br />
Do you have any idea on how to get this fixed ?<br />
<br />
(I'm looking with EXPLAIN SELECT ..., but the index is not listed as &quot;possible_keys&quot;).]]></description>
            <dc:creator>Aurelien PANIZZA</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 28 Aug 2012 08:50:20 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,565839,565839#msg-565839</guid>
            <title>always uses filesort even after adding indexes (1 reply)</title>
            <link>http://forums.mysql.com/read.php?115,565839,565839#msg-565839</link>
            <description><![CDATA[ Created a table with a interger column as index and then fired following query :<br />
<br />
EXPLAIN SELECT score FROM score_history ORDER BY score;<br />
<br />
this shows &quot;using index&quot; under the section &quot;extra&quot; in output.<br />
<br />
But when i fire :<br />
<br />
EXPLAIN SELECT * FROM score_history ORDER BY score;<br />
<br />
this shows &quot;using filesort&quot; under the section &quot;extra&quot; in output.]]></description>
            <dc:creator>Pranav Gore</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Thu, 23 Aug 2012 04:52:11 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,565766,565766#msg-565766</guid>
            <title>Simple query spending too much time in 'statistics' state without reason (3 replies)</title>
            <link>http://forums.mysql.com/read.php?115,565766,565766#msg-565766</link>
            <description><![CDATA[ Hello,<br />
<br />
I have a simple query on a single table which contains millions of rows.<br />
<br />
SELECT a, c<br />
FROM mytable<br />
WHERE a IN (list of ids)<br />
    AND b IN (list of others ids)<br />
<br />
The table 'mytable' has a primary index on (a, b). Both a and b are integer.<br />
I use InnoDB.<br />
<br />
CREATE TABLE `mytable` (<br />
  `a` INT(11) NOT NULL DEFAULT '0',<br />
  `b` INT(11) NOT NULL DEFAULT '0',<br />
  `c` INT(11) NOT NULL DEFAULT '0'<br />
  PRIMARY KEY (`a`,`b`,`c`),<br />
  KEY `speed2` (`a`,`c`)<br />
) ENGINE=INNODB DEFAULT CHARSET=latin1<br />
<br />
SHOW TABLE STATUS LIKE '%mytable%';<br />
NAME	ENGINE	VERSION	ROW_FORMAT	ROWS	AVG_ROW_LENGTH	Data_length	Max_data_length	Index_length	Data_free	AUTO_INCREMENT	Create_time	Update_time	Check_time	COLLATION	CHECKSUM	Create_options	COMMENT<br />
mytable	INNODB	10	COMPACT	267184317	82	21978152960	0	8147435520	7340032	2012-08-16 15:04:48	latin1_swedish_ci	<br />
<br />
The query takes quite a long time so I wanted to investigate and I found out with SHOW PROFILE that most of the time (98%) is spent in the state 'statistics'.<br />
<br />
The 'statistics' state is used by MySQL to calculate statistics to develop a query execution plan (which indexes to use and which order to join tables). There is no JOIN in this query and I tried to 'USE INDEX(PRIMARY)' or 'FORCE INDEX(PRIMARY)' but it doesn't change anything.<br />
<br />
So it does not make sense at all to me. Any idea why time is spent in 'statistics' state and how I could run my query faster?<br />
<br />
Thanks<br />
<br />
Vincent]]></description>
            <dc:creator>Vincent B.</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Tue, 28 Aug 2012 07:53:14 +0000</pubDate>
        </item>
        <item>
            <guid>http://forums.mysql.com/read.php?115,565624,565624#msg-565624</guid>
            <title>STRAIGHT_JOIN for OUTER JOINGS (1 reply)</title>
            <link>http://forums.mysql.com/read.php?115,565624,565624#msg-565624</link>
            <description><![CDATA[ I am running a query like this:<br />
<br />
SELECT a.key, a.col_1, b.col_1 FROM (SELECT * FROM table_a ORDER BY a.key LIMIT 100) a JOIN (SELECT * FROM table_b) b ON a.key=b.key;<br />
<br />
It turns out that using STRAIGHT_JOIN rather than INNER JOIN is much better in performance. (2x - 3x as fast)<br />
<br />
However, what I actually need is LEFT OUTER JOIN rather than INNER JOIN. Using simply LEFT JOIN have more or less the same performance as INNER JOIN. I guess LEFT JOIN is actually using the same algorithm to INNER JOIN rather than STRAIGHT JOIN.<br />
<br />
Is there a STRAIGHT_JOIN equivalence for OUTER JOIN?<br />
<br />
Thanks!]]></description>
            <dc:creator>Paul Tsui</dc:creator>
            <category>Optimizer &amp; Parser</category>
            <pubDate>Mon, 20 Aug 2012 11:16:01 +0000</pubDate>
        </item>
    </channel>
</rss>
