Skip to content

count query is very slow ( got a solution though ) #85

@reneweteling

Description

@reneweteling

Hey there,

I noticed two things on the count query, one is that the select stays in tact while you are only creating a count, thats extremely slow. I understand why you did it, to make all the sql specific stuf still working. Only.... its slow so ive got a little fix for that. And you execute the count query twice. And allot of times the count query is the same ( in my application its always the same ) so ive added a remember chain to it

    private function count($count  = 'count_all')
    {   

        //Get columns to temp var.
        if($this->query_type == 'eloquent') {
            $query = $this->query->getQuery();
            $connection = $this->query->getModel()->getConnection()->getName();
        }
        else {
            $query = $this->query;
            $connection = $query->getConnection()->getName();
        }

        // little magic to speed things up ( notice the clone, so it wont interfere with the rest of the code )
        $myQuery = clone $query;
        $myQuery->select( DB::Raw("'1' as row") );

        // notice that im using myQuery instead of query and ive added the rememeber to the mix
        $this->$count = DB::connection($connection)
        ->table(DB::raw('('.$myQuery->toSql().') AS count_row_table'))
        ->setBindings($myQuery->getBindings())->remember(1)->count();

    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions