【问题标题】:Force Index in cakephp 3.3 querycakephp 3.3 查询中的强制索引
【发布时间】:2017-11-20 14:15:50
【问题描述】:

我正在使用 CakePHP 3.3 并尝试使用以下查询获取有关收入的一些统计数据

 $this->Bookings
    ->find('all')
    ->select(['total' => 'sum(total_price)'])
    ->join($joinTables) // It has product and few other tables
    ->where(["P.id = '" . $product_id . "'"])
    ->where(["Bookings.booking_status != 'CANCELLED'"])
    ->where(["Bookings.booking_date >= '" . $last6MonthDate->format('Y-m-d') . "'"]);

此查询使用 (product_id, booking_status) 上的索引,但我希望此查询使用我在 (product_id, booking_date) 上创建的索引,这样查询速度会更快。在上述查询之前,我尝试使用以下行。

$this->Bookings->useIndex = 'FORCE INDEX(idx_product_id_booking_date)';

这不会将 FORCE INDEX 子句添加到我的查询中,因此 MySQL 会自动使用索引 idx_product_id_booking_status

类似问题的答案适用于 CakePHP 的早期版本,不适用于 CakePHP 3.3。请帮忙。

【问题讨论】:

    标签: mysql cakephp indexing cakephp-3.0 query-builder


    【解决方案1】:

    这个例子展示了如何在selectjoin 语句中使用索引:

    
    $this->loadModel('MainModel');
    $query = $this 
        ->MainModel
        ->select(['MainModel.id' ])
        ->from('main_model MainModel USE INDEX (PRIMARY)')
        ->join([
             'table' => 'other_model OtherModel USE INDEX (PRIMARY)',
             'conditions' => 'OtherModel.id = MainModel.other_model_id'
        ]);
    
    
    

    这将产生:

    SELECT MyModel.id
    FROM my_model MyModel USE INDEX (PRIMARY)
    INNER JOIN my_other_model MyOtherModel USE INDEX (PRIMARY)
    ON MyModel.id = MyModel.my_model_other_id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-30
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      相关资源
      最近更新 更多