Getting Doctrine to use MySQL “FORCE INDEX”

2019-05-23 09:06发布

I have a query in Doctrine's DQL that needs to be able to use MySQL's "FORCE INDEX" functionality in order to massively reduce the query time. Below is what the query basically looks like in plain SQL:

SELECT id FROM items FORCE INDEX (best_selling_idx)
WHERE price = ... (etc)
LIMIT 200;

I assume I have to extend some Doctrine component to be able to do this with DQL (or is there a way to inject arbitrary SQL into one of Doctrin's queries?). Anyone have any ideas?

Thanks!

3条回答
狗以群分
2楼-- · 2019-05-23 09:41

See the Native SQL part of the Doctrine documentation. You should be able to use RawSql to accomplish this.

查看更多
甜甜的少女心
3楼-- · 2019-05-23 09:42

If you don't like native SQL, you can use the following patch. https://gist.github.com/arnaud-lb/2704404

This patch suggests to create only one custom Walker and set it up as follows

$query->setHint(Query::HINT_CUSTOM_OUTPUT_WALKER, 'UseIndexWalker');
$query->setHint(UseIndexWalker::HINT_USE_INDEX, 'some_index_name');
查看更多
叼着烟拽天下
4楼-- · 2019-05-23 09:48

I've found very few helpful Doctrine_RawSql examples online, so here's what I ended up doing to create my query.

$q = new Doctrine_RawSql();
$q->select('{b.id}, {b.description}, {c.description}')
  ->from('table1 b FORCE INDEX(best_selling_idx) INNER JOIN table2 c ON b.c_id = c.id')
  ->addComponent('b', 'Table1 b')
  ->addComponent('c', 'b.Table2 c');
查看更多
登录 后发表回答