首頁 > php框架 > Laravel > laravel學習記錄之強制指定索引進行查詢

laravel學習記錄之強制指定索引進行查詢

藏色散人
發布: 2021-11-05 14:20:45
轉載
2754 人瀏覽過

為何必須強制指標為時?

資料庫沒有使用我們所設想的索引進行sql查詢,導致查詢特別慢。

mysql強制索引查詢語句

  • #select * from user where age = 26 force index(age); / / 強制索引

  • select * from user where age = 26 use index(age); // 優先依照這種索引來找出

#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

/**

 * 检测某个表中是否存在某个索引

 * @param $table

 * @param $index

 * @return bool

 * @author zhaohao

 * @date 2019-08-26 17:42

 */

if(!function_exists('hasIndex')) {

    function hasIndex($table, $name)

    {

        $conn = IlluminateSupportFacadesSchema::getConnection();

        $dbSchemaManager = $conn->getDoctrineSchemaManager();

        $doctrineTable = $dbSchemaManager->listTableDetails($table);

        return $doctrineTable->hasIndex($name);

    }

}

登入後複製
  • 在laravel的程式碼裡面需要這樣寫:

在這裡用when方法來判斷此索引是否存在,日過不存在的話就不用這個索引,不然會報錯,避免有人誤刪索引後,導致系統報錯。

此處強制索引的語句是:

1

->from(DB::raw('`erp_agents` FORCE INDEX (`test`)'))

登入後複製

例如:

1

2

3

4

5

6

7

8

9

10

11

12

13

$agents = Agent::where($whereType)

            ->when(hasIndex('Agent', 'test'),function ($q){

                $q->from(DB::raw('`erp_agents` FORCE INDEX (`test`)'));

            })

            ->when(request('position',false),function ($q){

                $q->whereIn('position_id',request('position'));

            })

            ->whereIn('agents.status', $validStatus)

            ->where('worked_at', '<=', $end)

            ->where('is_suppose', 0)

            ->addDomination('m.statistics-human-view')

            ->leftJoin('positions', 'positions.id', '=', 'agents.position_id')

            ->get(['worked_days', 'worked_at']);

登入後複製

【相關推薦:最新的五個Laravel影片教學

以上是laravel學習記錄之強制指定索引進行查詢的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板