等于零的地方是如此之慢

问题描述 投票:3回答:2

我正在使用Laravel 5.6和MySQL for DB

public function getTopPaid(){
    $books = Book::with('users')->where('price', '>', 0 )->get()
        ->sortByDesc(function ($book){
            return $book->users->count();//sorting by purchased users count
        })->take(25);
    return new BooksWithAuthors($books);
}

我想通过上面的代码获得购买最多的付费书籍。这很好,响应时间是1700毫秒。大约有400条记录。

但是下面的代码几乎是一样的:

public function getTopFree(){
    $books = Book::with('users')->where('price', '=', 0 )->get()
        ->sortByDesc(function ($book){
            return $book->users->count();
        })->take(25);
    return new BooksWithAuthors($books);
}

结果中只有34条记录,但RESPONSE是8000毫秒。并且代码中唯一的区别是“相等”

where('price', '>', 0 ) 

where('price', '=', 0 )

为什么第二个查询这么慢?以及如何解决这个问题

php mysql laravel laravel-5.6 mysql-8.0
2个回答
0
投票

默认情况下,MySQL在BTREE中存储它的索引。一般没有哈希。

性能差异的简短答案是>表单评估更多节点然后=表单。


0
投票

如果您经常使用价格列进行搜索,则可以考虑在该列中添加索引以提高性能:

CREATE INDEX books_price_idx ON books (price)
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.