MySQL optimization: do maths inside or outside a query?

I have a strong feeling that all mathematical operations unnecessary to the query itself must be pre-formed outside the query. For instance:

$result = mysql_query(SELECT a, a*b/c as score FROM table)
while ($row = mysql_fetch_assoc($result))
{
    echo $row['a'].' score: '.$row['score'].<br>;
}

against

$result = mysql_query(SELECT a, b, c FROM table)
while ($row = mysql_fetch_assoc($result))
{
    echo $row['a'].' score: '.$row['a']*$row['b']/$row['c'].<br>;
}

the second option is usually better, especially with complex table joins and the like. This is my suspicion, I lack confirmation.,.

+3
source share
7 answers

My feeling would be that the math in the database would be a bit more efficient in the long run, given your query setup. With the version of select a,b,cPHP should create 3 elements and fill them for each selected line.

2 , 33%. , , .

, b c, , , // .

, . , , , , , .

+1

. , /.

/, , .

+1

, , , WHERE. :

SELECT a, b, c FROM table WHERE a*b=c

.

SELECT a*b/c FROM table

.

+1

, . , , PHP.

- PHP . , . , , . , , . PHP .

- , -. -, .

, . , , .

+1

- , , , , , .

, , .

, , , , . , , SQL.

0

, , , . , .

0

I doubt this could be a bottleneck.
especially with complex table joins, etc., where one file array will come from these mathematical expressions 1000 times

However, you can always transfer your query using the BENCHMARK keyword and take some measurements

BENCHMARK 1000 SELECT a, a*b/c as score FROM table
-1
source

Source: https://habr.com/ru/post/1795824/


All Articles