2013-09-28 89 views
28

我有以下的mySQL查询,完美的工作。除了我需要添加一个“FORCE INDEX”,我不确定我在哪里必须这样做。我尝试了几乎每个位置,并总是收到一个mySQL错误。我究竟做错了什么?FORCE INDEX mySQL ...我把它放在哪里?

这里是原始查询:

$sql_select_recent_items = $db->query("SELECT * FROM (SELECT owner_id, product_id, start_time, price, currency, name, closed, active, approved, deleted, creation_in_progress FROM db_products ORDER BY start_time DESC) as resultstable 
WHERE resultstable.closed=0 AND resultstable.active=1 AND resultstable.approved=1 AND resultstable.deleted=0 AND resultstable.creation_in_progress=0 
GROUP BY resultstable.owner_id 
ORDER BY start_time DESC"); 

查询构造这种方式让我可以做“ORDER BY”中的“GROUP BY”之前,如果你想知道。

我需要补充的是:

FORCE INDEX (products_start_time) 

我想它几乎无处不在没有成功,这使我相信,有我失去了一些东西更复杂?

回答

39

索引提示的语法如下记载:
http://dev.mysql.com/doc/refman/5.6/en/index-hints.html

指数指数的走表引用之后:

SELECT * FROM (
    SELECT owner_id, product_id, start_time, price, currency, name, closed, 
     active, approved, deleted, creation_in_progress FROM db_products 

    FORCE INDEX (products_start_time) 

    ORDER BY start_time DESC) as resultstable 
    WHERE resultstable.closed=0 
    AND resultstable.active=1 
    AND resultstable.approved=1 
    AND resultstable.deleted=0 
    AND resultstable.creation_in_progress=0 
    GROUP BY resultstable.owner_id 
    ORDER BY start_time DESC 

警告:

如果”在GROUP BY之前使用ORDER BY得到l每个owner_id都有一个入口,你正在使用一个非标准且没有记录的MySQL来做到这一点。

不能保证它会继续在未来版本的MySQL中工作,并且查询可能在任何其他RDBMS中都是错误的。

标签中搜索有关此类查询的更好解决方案的许多解释。

+0

非常感谢!这工作完美,现在做这项工作,而我寻找更好的解决方案:) – user2643870