How to effectively use the result of a function call in a MySQL query several times without calling the function several times?

I have a SQL query like:

SELECT blah
  FROM table
 WHERE field1 % functCall(otherField1, otherField2) = 0
    OR field2 % functCall(otherField1, otherField2) = 0
    OR field3 % functCall(otherField1, otherField2) = 0

Is there a way that I can only call functCall once, reusing leads to two other comparisons?

Thank!

+3
source share
3 answers

MySQL automatically optimizes your query, so that the function is called only once, and the result will be reused.

If you want to avoid repeated code, you can evaluate the function in the view and then query for it.

SELECT blah
FROM
(
    SELECT 
        blah, field1, field2, field3,
        functCall(otherField1, otherField2) AS f
    FROM your_table
) T1
WHERE field1 % f = 0
   OR field2 % f = 0
   OR field3 % f = 0
+2
source

Save the result of the function in a variable first, using it in your query.

0

from, :

 SELECT blah
 FROM
   (select functCall(f1, f2) as fc, f1, f2, f3 from table) as t 
 WHERE f1 % fc = 0
    OR f2 % fc = 0
    OR f3 % fc = 0
0

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


All Articles