C
C
chelkaz2017-05-09 20:37:04
Laravel
chelkaz, 2017-05-09 20:37:04

Laravel. Why is there a hundreds of times difference in time requests?

If I do this:

\DB::table('ratings')
        ->selectSub(function ($query) {
            return $query->selectRaw('SUM(ecology)');
        }, 'ecology')
        ->selectSub(function ($query) {
            return $query->selectRaw('SUM(social_protection)');
        }, 'social_protection')

        ->where('point', 'test')
        ->first();

The result is instantly
"time" => 2.0
The SQL itself is like this:
select (select SUM(ecology)) as `ecology`,
(select SUM(social_protection)) as `social_protection`
from `ratings` where `point` = ? limit 1

But if I do it directly via select :
\DB::select('select (select SUM(ecology)) as `ecology`,
(select SUM(social_protection)) as `social_protection`
from `ratings` where `point` = ? limit 1', ['test'])

That time increases hundreds of times!!!
"time" => 787.87
Although the SQL query is the same:
select (select SUM(ecology)) as `ecology`,
(select SUM(social_protection)) as `social_protection`
from `ratings` where `point` = ? limit 1

Why such difference?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Philipp, 2017-05-18
@chelkaz

The fact is that when you pass a number instead of a string, an implicit call to CAST occurs .
Most likely your point is a string type and therefore CAST() is performed for each line, which significantly increases the code execution time.
I will add a description of your scenario
When comparing a string column to a number, MySQL cannot use the index to look up the value.

A
Alex Wells, 2017-05-11
@Alex_Wells

The stupidest question, because there is no point in using pure SQL, so it would be possible to score. I subscribe under the answer Nurlan

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question