Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL referencing, to avoid repeating myself?

Tags:

mysql

I have this snippet:

SELECT 
    CASE WHEN
        AVG(UNIX_TIMESTAMP(tDone)-UNIX_TIMESTAMP(tIPN))/3600 >= 10
    THEN
        ROUND(AVG(UNIX_TIMESTAMP(tDone)-UNIX_TIMESTAMP(tIPN))/3600,0)
    ELSE
        ROUND(AVG(UNIX_TIMESTAMP(tDone)-UNIX_TIMESTAMP(tIPN))/3600,1)
    END 
FROM
    ...

Can I do anything to remove the duplication from this? Something along these lines, for instance: (Hypothetical code follows):

SET var = AVG(UNIX_TIMESTAMP(tDone)-UNIX_TIMESTAMP(tIPN))/3600
SELECT 
    CASE WHEN
        var > 10
    THEN
        ROUND(var,0)
    ELSE
        ROUND(var,1)
    END 
FROM
    ...
like image 529
Codemonkey Avatar asked Oct 19 '22 21:10

Codemonkey


2 Answers

With a subquery you can do something like this :

SELECT 
  CASE WHEN avgtiPN >= 10 THEN ROUND(avgtiPN,0) ELSE ROUND(avgtiPN,1) END 
FROM 
  (SELECT 
     AVG(UNIX_TIMESTAMP(tDone)-UNIX_TIMESTAMP(tIPN))/3600 AS avgtiPN
   FROM
    ...) AS AVGQuery

But I am still uncertain if it is more readable.

like image 162
ForguesR Avatar answered Oct 22 '22 00:10

ForguesR


Yes, you can, but variable processing order is undefined for user-defined variables. This reference in the MySQL documentation explains when this works and when it doesnt.

like image 24
tony gil Avatar answered Oct 22 '22 01:10

tony gil